Highlight links an corresponding images on hover

偶尔善良 提交于 2020-01-07 04:51:05

问题


Working on a project an need a specific effect on the homepage. When a user hovers over the links in the nav the link is highlighted as well as the corresponding thumbnail on the page. Each of the links/thumbnails have classes an how we have it setup now is that on hover we search for the the element with the same class. Just wondering if there is a better way to go about doing this. Thanks.

(The layout of the page has the links on the left side an the thumbs in the "main" container which fills out that rest of the page)

$('#homeCatNav li a, #homeThumbsUlHolder li img').hover(function(e){
    var $thisA = $(this),
        $thisClass = $(this).attr("class");

    if (e.type.toLowerCase() === 'mouseenter') {
        $('li.imgToHighlight').find('img'+'.'+$thisClass).addClass('hoverElem');
        $('li.homeArtNameList').find('a'+'.'+$thisClass).addClass('hoverElem');             
    }
    if (e.type.toLowerCase() === 'mouseleave') {
        $('li.imgToHighlight').find('img').removeClass('hoverElem');
        $('li.homeArtNameList').find('a').removeClass('hoverElem');
    }
});

回答1:


i think you are complicating the event handler why just do it like this

$("'#homeCatNav li a, #homeThumbsUlHolder li img").hover(mouseOver, mouseOut);

function mouseOver() {
     $thisClass = $(this).attr("class");
     $('li.imgToHighlight').find('img'+'.'+$thisClass).addClass('hoverElem');
     $('li.homeArtNameList').find('a'+'.'+$thisClass).addClass('hoverElem'); 
}

function mouseOut() {
   $thisClass = $(this).attr("class");
   $('li.imgToHighlight').find('img').removeClass('hoverElem');
   $('li.homeArtNameList').find('a').removeClass('hoverElem');
}



回答2:


I would switch to "rel", but it doesn't really matter :

$('#homeCatNav li a, #homeThumbsUlHolder li img').hover(function(){
        var $thisA = $(this),
        $thisRel = $thisA.attr("rel");
        $('li.imgToHighlight').find('img[rel'+$thisRel+']').addClass('hoverElem');
        $('li.homeArtNameList').find('a[rel'+$thisRel+']').addClass('hoverElem');             
    },function(){
        $('li.imgToHighlight').find('img').removeClass('hoverElem');
        $('li.homeArtNameList').find('a').removeClass('hoverElem');
});


来源:https://stackoverflow.com/questions/6189968/highlight-links-an-corresponding-images-on-hover

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!