JavaScript連載36-上傳文件以及獲取input表單焦點

1、表單標籤焦點

<input type="text" placeholder="請輸入姓名">
    <script>
        window.onload = function (ev) {
            var input = document.getElementsByTagName("input")[0];
            //1.得到焦點,也就是按下鼠標的那個光標
            input.onfocus = function (ev1) {
                //this是一個指針用於指向變量
                this.style.width = '600px';
                this.style.height = '40px';
                this.style.outline = 'none';
                this.style.fontSize = '20px';

            }
            //2.失去焦點
            input.onblur = function (ev2) {
                this.style.border = '10px solid red';
                this.style.height = '40px';
            }
        }
    </script>
  • 不點擊輸入輸入框時的默認樣式
    36.1
  • 點擊了輸入框以後
    36.2
  • 再點擊其餘空白處的時候
    36.3

2、對上傳文件進行格式篩選

<label for="">上傳圖片:</label>
    <input type="file" id="file"><!--file就是上傳文件的按鈕-->
    <!--jpg png gif 格式的圖片才能上傳-->
    <script>
        window.onload = function (ev) {
            //1.獲取標籤
            var file = document.getElementById("file");
            //2.監聽做用域的變化
            file.onchange = function (ev2) {
                console.log("上傳文件了");
                //2.1獲取用戶上傳文件的內容
                var path = this.value; //this.value就是上傳文件的地址
                //2.2截取
                var suffix = path.substr(path.lastIndexOf('.'));//字符串操做函數substr,一個參數表明那那裏截取到最後的字符
                //lastIndexOf()最後某個字符的索引值
                console.log(suffix);

                //2.3大小寫轉換一下
                var lowerSuffix = suffix.toLowerCase();//轉換成小寫
                //2.4判斷
                if(lowerSuffix === ".jpg" || lowerSuffix === '.png' || lowerSuffix === '.gif'){
                    alert("上傳成功");
                }else{
                    alert("上傳格式不正確,只能jpg\\png\\gif");
                }

            }
        }
    </script>
  • 上傳一個文件不是.jpg.png.gif後綴的
    36.4
  • 上傳一張圖片1.jpg
    36.5

3、源碼:

  • D36_1_CommonAffairOfInputLable.html
  • D36_2_FormatVerificationOfUploadingImage.html
  • 地址:https://github.com/ruigege66/JavaScript/blob/master/D36_1_CommonAffairOfInputLable.html
  • https://github.com/ruigege66/JavaScript/blob/master/D36_2_FormatVerificationOfUploadingImage.html
  • 博客園:https://www.cnblogs.com/ruigege0000/
  • CSDN:https://blog.csdn.net/weixin_44630050?t=1
  • 歡迎關注微信公衆號:傅里葉變換,我的帳號,僅用於技術交流
    911
相關文章
相關標籤/搜索