首页 > 解决方案 > javascript更改父元素样式

问题描述

我有一个工作代码为 html 中的当前元素添加下划线,当我再次点击时我想清理它

var button = document.getElementsByTagName("button");
for (var i = 0; i < button.length; i++) {
  button[i].addEventListener('click', function() {
    this.parentElement.getElementsByTagName('span')[0].style = "text-decoration:line-through";
    if (this.parentElement.style == 'text-decoration:line-through') {
      this.parentElement.getElementsByTagName('span')[0].style = "text-decoration:none"
    }
  });
}
<!doctype html>
<html>
<body>
  <div id="tasks">
    <div>
      <button>Finish</button>
      <span>Finish web tasks</span>
    </div>
    <div>
      <button>Finish</button>
      <span>Go to gym</span>
    </div>
    <div>
      <button>Finish</button>
      <span>Clean home</span>
    </div>
    <div>
      <button>Finish</button>
      <span>Start project</span>
    </div>
    <div>
      <button>Finish</button>
      <span>Prepare to calculus</span>
    </div>
  </div>

</body>

</html>

标签: javascripthtmlcss

解决方案


只需检查是否 textDecoration == 'line-through',如果没有将其设置为 'line-through',如果是,将其设置为 'none'

<!doctype html>
<html>

  <head>
	
   
  </head>



  <body>
    <div id="tasks">
      <div>
      	<button>Finish</button>
      	<span>Finish web tasks</span>
      </div>
      <div>
      	<button>Finish</button>
      	<span>Go to gym</span>
      </div>
      <div>
      	<button>Finish</button>
      	<span>Clean home</span>
      </div>
      <div>
      	<button>Finish</button>
      	<span>Start project</span>
      </div>
      <div>
      	<button>Finish</button>
      	<span>Prepare to calculus</span>
      </div>
    </div>
    <script type="text/javascript">
    	var button = document.getElementsByTagName("button");
    	for(var i = 0; i<button.length;i++){
button[i].addEventListener('click', function() {
    				if(this.parentElement.style.textDecoration == 'line-through'){
    					this.parentElement.style.textDecoration = 'none';
    				} else {
              this.parentElement.style.textDecoration = "line-through";
            }
    		});
    }
    </script>
  </body>

</html>


推荐阅读