2017-07-16 6 views
0

ここに私はコードをしようとしています 私はページ上の任意の要素をクリックしてターゲットがboxshadow、 と私は別の要素をクリックすることができますprevius要素は、そのboxshadowを失ったし、私はあなたがCSSを適用した後の要素のセレクターを追加し、提供セレクタを使用してこれらの要素を選択し、このどのように要素とターゲットをクリックするかは

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} 

答えて

2

のようなコードを使用しています。

適用された属性を選択して適用された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>

0

これは、クラスを削除/追加することにより、スタイリングを変更する方が簡単です。

オブジェクトを使用すると、現在どの要素にシャドウがあるのか​​を追跡し、そこからクラスを削除できます。

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; 
} 
+0

あなたはそれでトラブルに実行されているので、もしブラウザは、.classListをサポートしていない場合が古い、this.target.className + = "ハイライト" を使用します。追加するにはthis.target.className = this.target.className.replace(new RegExp( "highlight"、 "g")、 "");削除する。 –

関連する問題