简体   繁体   English

滚动时添加文本阴影(jQuery或javascript)

[英]Add a text shadow when scrolled (jquery or javascript)

i have this html and css code: 我有这个HTML和CSS代码:

<div class="header">

</div>

.header {
    top:0;
    left:0;
    right:0;
    width:100%;
    background:#3b5998;
    height:95px;
    margin-bottom: 50px;
position:fixed;
}

What i'm trying to do here is the header should be in the fixed position (top) whenever the user scrolls down. 我在这里尝试做的是,每当用户向下滚动时,标题都应处于固定位置(顶部)。 I have no problem with that. 对于那件事我没有任何疑问。 I easily accomplished that task. 我轻松完成了这项任务。

I want to add a different styling on it when the user scrolls down. 当用户向下滚动时,我想在其上添加其他样式。 I want to add a box shadow effect on it when the user scrolls down so it will look elevated. 我想在用户向下滚动时在其上添加框阴影效果,以使其看起来升高。 If the user scrolls up and reached the top portion of my webpage, it will revert back to the default css style (which has no box shadow). 如果用户向上滚动并到达了我网页的顶部,它将恢复为默认的CSS样式(没有框阴影)。

More like saying: 更像说:

scrolled down = activate box shadow effect 向下滚动=激活框阴影效果

if scrolled up and reached the top = revert back 如果向上滚动并到达顶部=返回

I am not aware of any css code for this, maybe someone will help me with their javascript/jquery expertise to make a code? 我不知道有任何CSS代码,也许有人会用他们的javascript / jquery专业知识来帮助我编写代码?

sorry if my explanation is too long or a little confusing. 对不起,如果我的解释太长或有点混乱。 Thank you very much! 非常感谢你!

Try like this 这样尝试

$(window).scroll(function(){
if (document.body.scrollTop === 0)
     $(".header").css({"box-shadow":"none"});
else
     $(".header").css({"box-shadow":"0px 0px 1px #EEE"});
});

See Demo For Reference only 请参阅演示仅供参考

Something like this? 像这样吗

var win = $(window),
    doc = $(document),
    header = $('.header');

win.scroll(function(e) {
    var scrollPercent = win.scrollTop() / (doc.height() - win.height()),
        scrollPercentRounded = (scrollPercent * 100).toFixed(2);

    header.css({boxShadow: '0 0 ' + scrollPercentRounded + 'px #000'});
});

demo 演示

With this code you get a nice smooth transition: 通过此代码,您可以顺利过渡:

var $doc = $(document),
    $target = $('.header'),
    limit = 200,
    shadowStyle = '0 2px 5px',
    rgb = '0,0,0';

$(window).scroll(function() {
    var top = $doc.scrollTop();

    if (top <= limit) {
        var opac = 1/limit*top;
        $target.css('box-shadow', shadowStyle+' rgba('+rgb+','+opac+')');
    }
});

You can easily modify the shadow styles and limit to define on which range it should fade in/out. 您可以轻松修改阴影样式和limit以定义淡入/淡出的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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