简体   繁体   中英

jQuery change css on a specified element

I need something that will change the style of a div when you scroll to a specific element

Example:

In my header i have the texts: 1) Home 2) Text2 3) Text3 4) Text4

When on top i want the "Home" to be white and all the others blue When on paragraph 1 i want the "Text2" white and all the other blue When on paragraph 2 i want the "Text3" white and all the other blue When on paragraph 3 i want the "Text4" white and all the other blue When below "Text4" i want the "Home" to be white and all the others blue

PS: "Text2","Text3" and "Text4" will have nothing else in betwheen

I'd go with waypoints or with skrollr . There are plenty of tutorials about skrollr so dont worry.

You can do something like this

  1. Use scroll() to listen scroll event
  2. Get the scroll top value by using scrollTop()

DEMO :

 $(window).scroll(function() { $('#div2').css('color', $(this).scrollTop() > 390 ? 'red' : 'blue'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id=main style="height:1000px"> <div id=div2 style="margin-top:500px">element</div> </div> 

Check the following jquery functions

Your code could look something like that:

 ( function( $ ) { $(window).scroll(function(e){ var home = $('#home'); var switchPosition = $(window).scrollTop() + parseInt(home.css("top"))+30; $('.text').each(function(){ if ( switchPosition > $(this).offset().top && $(this).attr('data-color') !== home.attr('data-color') ) { home.css({color: $(this).attr('data-color')}); home.attr('data-color', $(this).attr('data-color') ); } }); }); } )( jQuery ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="home" style="font-weight: bold; color: blue; position: fixed; top: 20px; left: 20px;">HOME</div> <div style="color: white; position: fixed; top: 170px; left: 20px;">scroll down...</div> <div class="text" data-color="blue" style="background: #999; height: 500px"> </div> <div class="text" data-color="red" style="background: #666; height: 500px"> </div> <div class="text" data-color="white" style="background: #333; height: 1000px"> </div> 

You can use jQuery-

 $(document).ready(function() { $(window).scroll(function() { if ($(window).scrollTop()+$(window).height() > $('.yay').offset().top + $('.yay').outerHeight()) { $('.yay').css('background', 'black'); } else { $('.yay').css('background', 'red'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div style="background:blue;height: 2000px;color:white;font-size:30px;">Scroll Down</div> <div class="yay" style="background:red;height: 200px;"></div> <div style="background:blue;height: 300px;color:white;font-size:30px;">Scroll Up</div> 

This snippet will change the div background when it becomes fully visible in the viewport

Animating colors does not work unless you include a library for animating colors. jQuery does not animate colors by default.

So for color-animation you must include library like JQuery UI , but it is large for just using color-animation.

Instead i would suggest you to use Bitstorm:ColorLibrary , it's just 2.7kb in size.

JSFiddle : DEMO

 $(document).ready(function(){ var top = document.getElementById("css_text").scrollHeight; // top position of '#css_text' alert("Top position of #CSS_TEXT : " + top); var calcu = top - 20; $(window).scroll( function(){ var pos = $(window).scrollTop(); if(pos >= calcu) { $("#css_text").animate({"color":"red","opacity":"1"},2000); } }); }); 
 #css_text { opacity:0; color:blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors-min.js"></script> <h1>HTML Ipsum Presents</h1> <p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p> <h2>Header Level 2</h2> <ol> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> </ol> <blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote> <h3>Header Level 3</h3> <ul> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> </ul> <pre id="css_text"><code> #header h1 a { display: block; width: 300px; height: 80px; } </code></pre> <ul> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Aliquam tincidunt mauris eu risus.</li> <li>Vestibulum auctor dapibus neque.</li> </ul> 

This toggles the color of any header text at the point a matching element comes into view (or leaves) :

Demo

$(function() {

var gate = $(window),
bar = $('header'),
title = bar.find('span'),
element = $('.element'),
viewin, viewout;

gate.on('load resize', function() {

    viewin = []; viewout = [];

    element.each(function() {

    var placement = $(this).offset().top-gate.height(),
    dimension = $(this).outerHeight();

    viewin.push(placement);
    viewout.push(placement+dimension);
    });
})
.scroll(function() {

    var location = gate.scrollTop();

    element.each(function(i) {

    var option = title.eq(i), white = option.hasClass('white');

    if (location > viewin[i] && location <= viewout[i]) {
    if (!white) option.addClass('white');
    }
    else if (white) option.removeClass('white');
    });
});
});

Comments below are no longer very relevant because they are discussing an earlier stage.

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