本例說的應用場景好比有在input框架中輸入字符後,右邊會出現一個叉叉清除的按鈕,好比下圖:css
<input type="text" name="keyword" id="" placeholder="關鍵詞" style="width:200px" class=" input-text" value="{$keyword}" oninput="clearInput(this);">
function clearInput(obj) { let clearObj = document.getElementById("clear-input"); //動態生成的圖標對象 if(obj.value.length>0){//開始輸入時動態生成 if(!document.body.contains(clearObj)){//判斷圖標對象是否存在 var newNode = document.createElement("i"); newNode.style.cssText = "position:relative;left:200px;"; newNode.setAttribute("class","Hui-iconfont"); newNode.setAttribute("id","clear-input"); newNode.innerHTML = ""; obj.parentNode.insertBefore(newNode,obj);//js只有insertBefore,因此經過定位實現到最右邊 } }else{ obj.parentNode.removeChild(clearObj); //移除圖標對象 } }