开发者

Search for location.hash inside block

We are on the page http://site.com/movies/#posters

<div class="con开发者_StackOverflow社区tent">
    <div id="posters"></div>
</div>

I'm trying to use this code, for jump to block with id posters and add class active to it:

$(location.hash).addClass("active");

It works good, but has a problem. If there is a link like <a href="http://site.com/movies/actuale/#posters">Actuale</a>, it jumps to this link, not to <div id="posters"></div>

Should jump to block with id="posters inside class="content" block.

<div id="posters"></div> should become <div class="active" id="posters"></div>

How to do that?

Thanks.


You'll have to scroll to the element and prevent the link from firing.

Make a function to do this:

function ScrollToHash() {
    var posX = 0, posY = 0;
    var obj = document.getElementById(document.location.hash);
    while(obj) {
        posY += obj.offetTop;
        posX += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    window.scrollTo(posX, posY);
}

You'd also have to add an onclick handler to your link:

<a href="#posters" onclick="ScrollToHash(); return false;">Link</a>

The only problem is that document.location.hash gives you the hash value of the current page, not of the link. You'd have to find a different way to do that.

I may be misinterpreting what you're attempting to do, so hopefully this at least points you in the right direction.


Happy, I think you must be using duplicate IDs. $('#posters') will select an element with id="posters", not a link that simply contains #posters is the href attribute. I suggest you look at your HTML and make sure that the link isn't actually ID'd posters as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜