开发者

Javascript knocks out CSS:hover?

Hi im trying to make the Product Categories menu work on this page:

http://www.jaybrand.co.uk/p1.html

at the moment the page loads and CSS hover works to set the background position so that the graphic behind makes a roll over effect.

i put some javascript to set the background position to the roll over on click, but this knocks out the CSS hover:

onclick="setStyle('c1','backgroundPosition','0px 0px');

it means that c1:hover no longe开发者_StackOverflowr works.. i tried putting !important in the CSS c1:hover background position and this fixed it in Firefox but not IE.

How can i write something in Javascript to also say:

onclick="setStyle('c1:hover','backgroundPosition','-276px 0px');

......... i know Javascript does not do hyphens and the way to get for example "background-position" in CSS is to ditch the hyphen and make "P"osition capitol. perhaps something can be done also to get to the CSS hover attribute?


When you set an element's style.backgroundPosition, it's the same as setting an inline style="background-position: ..." attribute. Since inline style attributes override stylesheet rules, the hover/non-hover rules can never again affect the background position.

You could remove the backgroundPosition rule for elements being unselected so that the stylesheet rules can shine through. But really, your code needs a serious refactoring: manually setting every background position in the onclick is ugly and unmaintainable.

Instead, switch a class around to flag the selected link, eg. styled like this:

.c { background: url(...); }
#c1.selected, #c1:hover { background-position: -276px 0; }
#c2.selected, #c2:hover { background-position: -276px -61px; }
...

markup:

<h2><a class="c selected" id="c1" href="#productcats">Products</a></h2>
<a class="c" id="c2" href="#rice">Rice</a>
...

(a-inside-h2 because the other way around is invalid.)

script:

var selected= $('#c1');
$('.c').click(function() {
    // Move the 'selected' class to the new element
    //
    selected.removeClass('selected');
    selected= $(this);
    $(this).addClass('selected');

    // Scroll target element into view
    //
    var y= $(this.hash).offset().top-$('#slide').offset().top;
    $('#slide').animate({top: -y+'px'}, {duration: 450, queue: false});

    return false;
});

Note this uses the href of the links to point to where they go, which will improve accessibility on non-visual browsers. You should also add some code to look at the location.hash on page load and if you see something there, scroll that page into view. Otherwise, it will be impossible to bookmark one of your subpages, or to middle-click-new-tab the links or anything like that.


I was doing something similar the other day, not 100% sure but this might help push you in the right direction..

 onclick="document.getElementById('c1:hover').style.cssText='backgroundPosition: -276px 0px;';"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜