Javascript获取元素类或数据属性

时间:2015-06-12 15:56:24

标签: javascript html css

目前我有一个javascript函数,它会查找id并更改一些CSS。但是我希望这个函数在多个div上运行。因此,我需要我的函数来查找类或数据属性。请你能帮助我!

<script>
  var div = document.getElementById('hover')
  div.onclick = function () {
    this.style.width = '800px'
    this.style.transition = 'all 1s'
    this.style.backgroundColor = 'red'
  }
</script>

2 个答案:

答案 0 :(得分:1)

您需要使用class,这样会更好。然后循环播放!

<script>
  var divs = document.getElementsByClassName('hover');
  for (var i = 0; i < divs.length; i++)
    divs[i].onclick = function () {
      this.style.width = '800px'
      this.style.transition = 'all 1s'
      this.style.backgroundColor = 'red'
    }
</script>

使用addEventListener的示例:

<script>
  var divs = document.getElementsByClassName('hover');
  for (var i = 0; i < divs.length; i++)
    divs[i].addEventListener("click", function () {
      this.style.width = '800px'
      this.style.transition = 'all 1s'
      this.style.backgroundColor = 'red'
    }, false);
</script>

答案 1 :(得分:1)

您可以将所有元素包装在公共父级中,然后将click事件处理程序应用于该父级,检查发起该事件的target

这样做需要将事件仅附加到单个元素(而不是每个元素)。

另外,你的样式应该在CSS中作为一个类声明,所以你只需要切换那个特定的类(并且总是更好地保持css免受javascript的影响,以保持可持续性)

这是一个简单的示例http://codepen.io/anon/pen/jPwXVr

CSS

.open {
  width: 800px;
  -webkit-transition  : all 1s;
  -moz-transition  : all 1s;
  transition  : all 1s;
  background: red;
}

JS

 document.getElementById('wrap').addEventListener('click', function(ev) {
  var target = ev.target
  if (target.nodeName === 'DIV') {
      target.className = 'open';        
  } 
}, false);

如果标记的结构使得不可能使用公共包装器,则可以在body元素上附加事件,如此

http://codepen.io/anon/pen/aOwPWY?editors=011

CSS

.element {
  width: 800px; 
  -webkit-transition  : all 1s;
  -moz-transition  : all 1s;
  transition  : all 1s;
}

.element.open {
  background: red;
}

JS

document.body.addEventListener('click', function(ev) {
   var t = ev.target;

   /* I used classList for the sake of brevity, check caniuse.com
      for its support across browser */

   if (t.classList.contains('element')) {
       t.classList.toggle('open');        
   } 
}, false);