清除每个文本框的按钮,如IE(Javascript)

时间:2014-08-03 14:13:16

标签: javascript html css

我希望每个文本框前面都有这样的Clear按钮来清除它的文本。您可以在Internet Explorer中看到此类清除按钮。但这是IE的默认功能。

我只能使用CSS,HTML和JAVASCRIPT ..遗憾的是我无法使用Jquery。那么有什么方法可以做到这一点吗?

由于

enter image description here

2 个答案:

答案 0 :(得分:0)

<强> Demo

的javascript

document.getElementById('inputClear').onclick = function () {
    document.getElementById('inputText').value = "";
};

HTML

<span class="deleteicon">
    <input id="inputText" value="input here" type="text" />
    <span id="inputClear"></span>
</span>

CSS

span.deleteicon {
    position: relative;
}
span.deleteicon span {
    position: absolute;
    display: block;
    top: 4px;
    right: 4px;
    width: 16px;
    height: 16px;
    background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
    cursor: pointer;
}
span.deleteicon input {
    padding-right: 20px;
}

答案 1 :(得分:0)

的JavaScript

window.onload = function(){
  var span = document.getElementsByClassName('clear'), i;
  for(i = 0; i < span.length; i++){
    (function(i){
      span[i].onclick = function(){
        span[i].parentNode.getElementsByTagName('INPUT')[0].value = ''; 
      };
    })(i);
  }
};

HTML

<form>
  <div class="wrapper">
    <input type="text" name="firstname" value="" class="textbox" />
    <span class="clear">x</span>
  </div>
  <div class="wrapper"> 
    <input type="text" name="lastname" value="" class="textbox" />
    <span class="clear">x</span>
  </div>
</form> 

CSS

.clear{
  position:absolute;
  top:2px;
  right:5px;
  cursor:pointer;
}

.textbox {
   width:100%;
}    

.wrapper {
  width:200px;     
  position:relative;
}  

Working jsBin


其他答案的旁注:假设只有一个元素而使用getElementById('clear')并不是一个好主意。