有没有办法突出书签的目标? (www.site.com/page.htm#bookmark)?

时间:2008-09-10 14:41:44

标签: javascript jquery css

我想链接到页面上的书签(mysite.com/mypage.htm#bookmark)并在视觉上突出显示已添加书签的项目(可能有红色边框)。当然,会有多个项目加入书签。因此,如果有人点击#bookmark2,那么 其他区域将被突出显示)。

我可以看到如何用.asp或.aspx做到这一点,但我想做的更简单。我想也许有一种聪明的方法可以用CSS来做。

为什么我感兴趣: - 我希望我们的程序链接到一个列出其上所有程序的购物页面。我正在使用书签,所以他们跳转到特定的程序区域(site.com/shoppingpage#Programx),但只是为了使它明显我想实际突出显示链接到的页面

4 个答案:

答案 0 :(得分:9)

在你的CSS中你需要定义

a.highlight {border:1px solid red;}

或类似的东西

然后使用jQuery,

$(document).ready ( function () { //Work as soon as the DOM is ready for parsing
    var id  = location.hash.substr(1); //Get the word after the hash from the url
    if (id) $('#'+id).addClass('highlight'); // add class highlight to element whose id is the word after the hash
});

要突出显示鼠标上的目标,请添加:

$("a[href^='#']")
    .mouseover(function() {
        var id  = $(this).attr('href').substr(1);
        $('#'+id).addClass('highlight');
    })
    .mouseout(function() {
        var id  = $(this).attr('href').substr(1);
        $('#'+id).removeClass('highlight');
    });

答案 1 :(得分:6)

您还可以在CSS中使用target伪类:

<html>
<head>

<style type="text/css">
div#test:target {
 background-color: yellow;
}
</style>

</head>
<body>

<p><b><a href="#test">Link</a></b></p>

<div id="test">
Target
</div>

</body>
</html>

不幸的是IE或Opera不支持目标伪类,所以如果你在这里寻找通用解决方案,这可能还不够。

答案 2 :(得分:2)

使用您喜欢的JS工具包将“突出显示”(或其他)类添加到包含(或包含在)锚点的项目中。

类似的东西:

jQuery(location.hash).addClass('highlight');

当然,如果您希望由页面上的其他链接触发,您需要打电话或点击,并且您需要定义.highlight类。您还可以根据要突出显示的容器使jQuery选择器向上或向下遍历。

答案 3 :(得分:0)

我想如果你能用JavaScript和cookie存储这些信息,以便记住书签的功能,如果你想与数据库进行交互,甚至可以添加一些Ajax。

CSS只能做样式。您必须为已添加书签的锚点提供CSS文件中的类。

CSS还有一个a:visited选择器,用于设置浏览器历史记录中的链接样式。