繁体   English   中英

如何单击任何元素,目标将切换到该元素

[英]how to click any element and target will switch to it

这是我尝试编写的代码,我希望我的鼠标在页面上的任何元素上单击,目标将变为boxshadow,在单击该元素之后,我可以单击另一个元素,previus元素将丢失其boxshadow,并且我正在使用像这样的代码

  document.onclick = function(evt){ 
  console.log('clicked');
  var target = null,
  target = evt.target;
  var obj = document.querySelector(target);
  obj.style.boxShadow = '3px 10px 100px yellow';
  if(target === 'null'){
   console.log('ye');
  obj.style.boxShadow = '0'; 
  obj = document.querySelector(target) 
  console.log(obj)}     
   return target}

应用CSS之后,添加元素选择器,然后使用提供的选择器选择那些元素。

通过选择应用的属性来删除应用的CSS。

 document.onclick = function(evt) { var target = evt.target; var pastElems = document.querySelectorAll('.shadowed'); [].forEach.call(pastElems, function(el) { el.style.boxShadow = 'none'; target.classList.remove('shadowed'); }) target.style.boxShadow = '3px 10px 100px yellow'; target.classList.add('shadowed'); } 
 .elem { width: 100px; height: 100px; border: 1px solid black; float: left; } 
 <div class='elem'></div> <div class='elem'></div> <div class='elem'></div> <div class='elem'></div> 

通过添加/删除类来更改样式更加容易。

如果使用对象,它将允许您跟踪当前具有阴影的元素并从中删除该类。

var setBoxShadow = {
  target: null,
  clearShadow: function() {
     if (this.target != null && this.target != undefined) {
         this.target.classList.remove("highlight");
     }
  },
  addShadow: function(newTarget) {
      this.target = newTarget;
      this.target.classList.add("highlight");
  },
}

body.onclick = function(evt) {
  setBoxShadow.clearShadow();
  setBoxShadow.addShadow(evt.target);
}

和CSS:

.highlight {
   box-shadow: 3px 10px 100px yellow;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM