js实现:仿京东搜索栏随滑动透明度渐变

来源:互联网 发布:如何安装网络摄像头 编辑:程序博客网 时间:2024/05/29 16:36

注意:不兼容IE8及以下,IE11和360的IE兼容模式测试通过====IE8不支持opacity

此效果采用的opacity做的透明渐变

demo效果

废话不多说,直接上代码:

1、HTML

<header class="module-layer">    <div class="module-layer-content">    <div class="search-box-cover"></div>        <p class="layer-return"></p>        <h1 class="layer-head-name">        <div class="pr search-box">        <img class="shop-search" src="images/search.png"/>        <input id="shop-input" type="text" placeholder="搜索店内商品" value="" />        </div>        </h1>        <p class="layer-share"></p>    </div></header>
其中search-box-cover就是控制透明度渐变的背景
2、css

.module-layer {width:100%;position:fixed;top:0;left:0;z-index:100000;}.module-layer-content {position:relative;min-width:320px;max-width:750px;width:100%;margin:0 auto;}.module-layer-bg {width:100%;height:100%;background:#000;opacity:.7;position:absolute;top:0;left:0;z-index:-1;}.layer-head-name {height:50px;line-height:50px;text-align:center;padding:0 50px;font-size:20px;}.layer-return,.layer-share {width:50px;height:50px;line-height:50px;text-align:center;position:absolute;top:0;z-index:1;}.layer-return {left:0;}.layer-share {right:0;}.pr {position:relative;}#shop-input::-webkit-input-placeholder {color:#fff;}#shop-input:-moz-placeholder {color:#fff;}#shop-input::-moz-placeholder {color:#fff;}#shop-input:-ms-input-placeholder {color:#fff;}#shop-input {border:none;outline:none;background:transparent;}.search-box {height:30px;border-radius:20px;top:10px;overflow:hidden;z-index:10;}.search-box:after {content:'';display:block;width:100%;height:30px;background:#fff;opacity:.5;position:absolute;top:0;left:0px;z-index:-1;}#shop-input {height:28px;line-height:28px;font-size:16px;position:absolute;top:0;left:30px;}

3、js

$(function(){   var $body = $('body');   var setCoverOpacity = function() {        $body.find('.search-box-cover').css({            opacity: ((($body.scrollTop() / 150) > 0.9) ? 0.9 : ($body.scrollTop() / 150))        })    }//初始化设置背景透明度    setCoverOpacity();//监听滚动条事件,改变透明度    $(window).scroll(function() {        setCoverOpacity();    });})

最终效果:



注意:

特别注意的一条:强制刷新,会导致页面的重新加载,所以动态加入的css样式不会存在,那么对透明背景的初始化非常重要,在网页端用户强制刷新,才不会失去透明效果。

1、

((($body.scrollTop() / 150) > 0.9) ? 0.9 : ($body.scrollTop() / 150))
此三目表达式是判断当前滚动条位置所在位置,如果位置值除以150大于0.9,就返回0.9,反之就返回那个小于等于0.9的值,将返回的值设置为背景的透明度就完成了。

2、由于滚动条的位置是动态获取的,所以设置透明度会不停改变,不用单独再做渐变的动画效果。

3、最终透明度问题,京东在最终背景设置的是0.9,所以本案例也采用的0.9,同时体验效果会更好。

4、滚动条位置导致的渐变,将150设置更大,渐变的距离会更长。

再次声明:不兼容IE8及以下



阅读全文
2 0