2016-07-30 54 views
0

我認爲標題是顯而易見的。我的網頁上有超鏈接,例如:點擊超鏈接和更改ID的ID

<a href="#box1">LINK1</a> 
<a href="#box2">LINK2</a> 

<div id="box1"> 
content 
</div> 
<div id="box2"> 
content 
</div> 

BOX1和BOX2沒有背景,但是當我點擊鏈接1,去BOX1,有沒有辦法來改變這種訪問框的CSS?

JsFiddle

+0

如果其中一個答案下面回答你的問題,這個網站的工作的工作方式,你會「接受」答案,更在這裏:[*當有人回答我的問題時,我應該怎麼做?](http:// stackoverfl ow.com/help/someone-answers)。但前提是你的問題確實得到了回答。如果不是,請考慮在問題中添加更多詳細信息。 – FrankerZ

回答

3

提取id

哈希返回#box1,它可以被用來作爲id選擇

使用attribute starts with選擇或選擇#box(Anything)元素

$('a[href^="#box"]').on('click', function() { 
 
    $(this.hash).css('background', 'green'); 
 
});
div { 
 
    width: 100%; 
 
    height: 400px; 
 
    border: 1px solid #ccc; 
 
} 
 
#c:focused { 
 
    background #d00; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<a href="#box1">LINK1</a> 
 
<a href="#box3">LINK2</a> 
 
<a href="#box2">LINK3</a> 
 

 
<div id="box1"> 
 
    content1 
 
</div> 
 
<div id="box2"> 
 
    content2 
 
</div> 
 
<div id="box3"> 
 
    content3 
 
</div>

1

一個簡單的草案添加一個簡單的onclick事件:從hash財產

<a href="#box1" onclick="$('#box1').css({backgroundColor: 'yellow'})">LINK1</a> 
0

使用.click()事件得到參考點擊的元素。

$(".link").click(function() { // create click event for anchor tag using class 
 
    var href = $(this).attr("href"); // get href value 
 
    href = href.replace("#",""); // remove # from href 
 
    $(".content").css("color","black"); // first change color to back of all div 
 
    $("#"+href).css("color","red"); // change css of div using href value as id 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="#box1" class="link">LINK1</a> 
 
<a href="#box2" class="link">LINK2</a> 
 

 
<div id="box1" class="content"> 
 
content 
 
</div> 
 
<div id="box2" class="content"> 
 
content 
 
</div>

0

一種解決方案使用jQuery如下:

$(function(){ 
 
    // attach a click handler for all links having the class js-link. 
 
    $(".js-link").click(function(){ 
 

 
     // clear the background of all boxes. 
 
     $(".js-box").css("background","000"); 
 
     
 
     // find the corresponding box's id. 
 
     var box = $(this).data("target"); 
 
     
 
     // sets it's background. 
 
     $(box).css("background", "#d00"); 
 
    }); 
 
});
div{ 
 
    width:100%; 
 
    height:400px; 
 
    border:1px solid #ccc; 
 
} 
 
#c:focused{ 
 
    background #d00; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#box1" class="js-link" data-target="#box1">LINK1</a> 
 
<a href="#box3" class="js-link" data-target="#box2">LINK2</a> 
 
<a href="#box2" class="js-link" data-target="#box3">LINK3</a> 
 
    
 
<div id="box1" class="js-box"> 
 
    content1 
 
</div> 
 
<div id="box2" class="js-box"> 
 
    content2 
 
</div> 
 
<div id="box3" class="js-box"> 
 
    content3 
 
</div>