简体   繁体   中英

Jquery Change background colour on Nav link mouseover

I want to change the color of background when I hover on different links in my nav menu. Say, link one.. the background goes to red, nav 2 the background goes to blue, nav 3 the background goes to green etc. But now, when i am on those pages, background to be the same as when the mouse hover over the links. So page 1 background will be red, page 2 = blue, page 3 = green etc.

Store the background-color info for all the links in cookies and when you visit one of these pages, get all the cookies and compare their values for your current page and set the background of that color.

For example when you hover over link1 set a cookie similar to this pair of string "link1color": "red" and so on. When you visit one of these pages get the cookies find the matching cookie for the page and get the background-color and update the background.

You can do something like this.

<a href="#" class="change-bg-color" data-bg-color="#ff0000">Link 1</a>
<a href="#" class="change-bg-color" data-bg-color="#00ff00">Link 2</a>
<a href="#" class="change-bg-color" data-bg-color="#0000ff">Link 3</a>

<script>
    $('a.change-bg-color').hover(function(){
        // Change you color
        $(body).css('background-color', this.getAttribute('data-bg-color') );
    },function(){
        // Back to the original color
        $(body).css('background-color', '#fff' ); // Supposing that #fff is your default bg color
    });
</script>

And if you want the "Link 1", "Link 2" and "Link 3" pages to have a different background color, the best way to do it should be to have a page-specific CSS class. It doesn't require javascript.

将您的背景色存储在数组中,并根据当前页面上的需要在js / jquery的帮助下从数组值中相应地更改值,因为如果数组是全局定义的,则您可以在应用程序中的任何位置进行快速访问而访问率低记忆。

Approach :

  1. Have three different classes in your CSS - say bkBlue, bkRed, bkGreen

    .bkBlue { background-color : 'blue' }

  2. Using on hover event, change the class applied to the link using addClass and removeClass.

  3. Store the current class value in a session variable.

  4. add the class from the session variable to the current page.

And one another method is keep different hover classes with different id/class, if nav is not in large numbers and attach that classes with your particular nav hover. I hope you understand because this is the easiest way. Gud luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM