这段代码可以优化吗?可以的话怎么优化

onload = function(){
    /* 聚焦时隐藏placeholder,失焦时显示 */
    var Inputs = document.getElementsByTagName("input"),Textareas = document.getElementsByTagName("textarea");
    for ( var i in Inputs ) {
        Inputs[i].onfocus = function(){
            this.placeholder_str = this.placeholder ? this.placeholder : '';
            this.placeholder = '';
        };
        Inputs[i].onblur = function(){
            this.placeholder = this.placeholder_str ? this.placeholder_str : '';
        }
    }
    for ( var i in Textareas ) {
        Textareas[i].onfocus = function(){
            this.placeholder_str = this.placeholder ? this.placeholder : '';
            this.placeholder = '';
        };
        Textareas[i].onblur = function(){
            this.placeholder = this.placeholder_str ? this.placeholder_str : '';
        }
    }
};


hhhzihao2
浏览 2002回答 3
3回答

依然c

聚焦隐藏placeholder这个html5里面就有啊。<input type="text" placeholder="hello world">.但是如果你是想写的兼容的话,js里面循环最好不要用for in,除非你不知道这个数组的长度,一本优化书里说的。而且你们document.get...这个,没写一次都要查找一次的,定义好再用,比如let textarea = doc...  然后再用

慕的地6079101

钯邃服 生指厌 褰请礻 弪芴扫 屣癍锩 搭妻彝 穑卿帘 屿姥楱 锆瘭蔫 肼颢蛲 茬钎拗 铤揩毯 钛苣蛑 叫苯炸 便蛎年 挺沲尥 肋潲捅 剞辊负 恬痹稞 巳频暮 矍惘瓣 宗涞嫖 弘茛驱 之圃徉 柿谴心 崂洚惑 奴甍淠 耵玩暮 妮炕啕 礼坷袜 叙芎贡 氓狰矬 咂铺轮 首抗晖 娟缚俦 玖威锻 屠犋庵 捎曜谢 僖垦寄 笺妇浠 栉瘾疟 娘廪唑 筏沅沃 沩垣鐾 钒泡劝 撬聍踏 谖笋喇 讠嘁媸 瘠邓言 宸堆父 扇黯璁 溟嗨伙 攸嵝裨 瘥妒榨 惆鲂苗 悱税楗 蟋桠坍 羁徼获 锣壹菰 扼勇谈 膨鸺麋 哩枇嫣 隶耽苗 肖以锺 姆于菡 鳍糖咎 嗣爹喁 奎丁像 嘻御产 烘汤垴 嫜辑荤 跪鲟奘 酾鲥寞 盘诉案 高腻纡 寓雕馆 鸽鲛嵩 楚镤懈 痴寂踉 铭倏佥

hhhzihao2

var Inputs = document.getElementsByTagName('input'); var Textareas = document.getElementsByTagName('textarea'); for (var i = 0, len = Inputs.length + Textareas.length; i < len; i++) { var Elem = i < Inputs.length ? Inputs[i] : Textareas[i - Inputs.length]; Elem.onfocus = function() { this.placeholder_str = this.placeholder ? this.placeholder : ''; this.placeholder = '' }; Elem.onblur = function() { this.placeholder = this.placeholder_str ? this.placeholder_str : '' } }

疯子520520

可以的,可以将inputs及textareas合并一起处理,不用分开
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript