我的span范围内有其他span类。跨度方块是链接的,因此该方块内的所有内容也是链接的。我想知道如果点击方形是否可以改变跨度方块的背景颜色?
谢谢你的回答!
答案 0 :(得分:2)
这就是为css制作的,所以我会先使用它,然后才能跳过'使用javascript。
我会使用:visited
选择器,用于选择访问过的链接。
:visited是一个用于锚链接元素的伪类选择器 当访问该锚链接的href属性时匹配 这个浏览器过去。 〜SOURCE
此用法的基本示例如下所示:
a:visited{
color:red;
}

<div>
<span><a href="#">1</a></span>
<span><a href="##">2</a></span>
<span><a href="###">3</a></span>
<span><a href="####">4</a></span>
</div>
&#13;
答案 1 :(得分:0)
var elements = document.querySelectorAll( "span" );
for( var e in elements ){
if( e.match( /\D/ ) continue;
elements[e].addEventListener &&
elements[e].addEventListener(
"click",
function(){ this.style.backgroundColor = "#800" }
) ||
elements[e].attachEvent &&
elements[e].attachEvent(
"onclick",
function(){ this.style.backgroundColor = "#800" }
);
}
答案 2 :(得分:0)
我更喜欢使用CSS并直接访问目标元素的解决方案(如果DOM包含数百个可能会产生噪音)
正如您在此代码段on jsfiddle中所看到的,您可以添加和删除CSS类以更改背景
.square{ width: 120px; height: 150px; display: inline-block;}
.green{ background-color: #11EE00}
.red{ background-color: #EE1100}
<span id="mySpan" class="square green">Hello world!</span>
window.onload = function() {
document.getElementById("mySpan").onclick = function () {
Change(this);
}
}
function Change(e){
removeClass(e, "green");
addClass(e,"red");
}
function addClass(element, classToAdd) {
var currentClassValue = element.className;
if (currentClassValue.indexOf(classToAdd) == -1) {
if ((currentClassValue == null) || (currentClassValue === "")) {
element.className = classToAdd;
} else {
element.className += " " + classToAdd;
}
}
}
function removeClass(element, classToRemove) {
var currentClassValue = element.className;
// removing a class value when there is more than one class value present
// and the class you want to remove is not the first one
if (currentClassValue.indexOf(" " + classToRemove) != -1) {
element.className = element.className.replace(" " + classToRemove, "");
return;
}
// removing the first class value when there is more than one class
// value present
if (currentClassValue.indexOf(classToRemove + " ") != -1) {
element.className = element.className.replace(classToRemove + " ", "");
return;
}
// removing the first class value when there is only one class value
// present
if (currentClassValue.indexOf(classToRemove) != -1) {
element.className = element.className.replace(classToRemove, "");
return;
}
}
addClass和removeClass credits
答案 3 :(得分:0)
尝试使用这样的css
<style type="text/css">
span.First span.Last
{
background-color: #BBBBBB;
}
a:visited span.First span.Last
{
background-color: #4cff00;
}
</style>
<a href="#">
<span class="First">
<span class="Last">blabla
</span>
</span>
</a>
答案 4 :(得分:0)
尝试使用javascript getElementByTagName() method :
window.onload=function(){
var square=document.getElementsByClassName("square")[0];
var x = square.getElementsByTagName("span");
for (var i=0; i<x.length; i++){
x[i].onclick=function(){
this.style.backgroundColor="red";
}
}
};