本例说的应用场景好比有在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); //移除图标对象 } }