jQuery 滚动条插件 jQuery custom content scroller 支持横向滚动纵向滚动以及多种滚动显示效果。使用这个插件你可以轻松的给你的层追加很好看的滚动条。
如图,当然可以根据自己的需要修改其颜色,滚动条的宽度
使用步骤
1. 引用 jQuery 类库极其相关的插件 js 和 css 库
- <link href="jquery.mCustomScrollbar.css" rel="stylesheet" type="text/css">
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
- <script src="jquery.mCustomScrollbar.concat.min.js"></script>
2. 给元素追加自定义滚动条方法:
- <script>
- (function($) {
- $(window).load(function() {
- $(".content").mCustomScrollbar();
- });
- })(jQuery);
- </script>
3. 如果需要横向滑动你可以这么设置
- $(".content").mCustomScrollbar({
- horizontalScroll: true
- });
转载地址: http://www.jq22.com/jquery-info124
效果地址: http://www.jq22.com/cj/customer/index.html
其中不错的插件:
Timeline
Timelinr
TimergliderJS
Chronoline
使用以上 jQuery 插件或者类库都可以创建漂亮的时间轴 timline 特效。
Timelinr 是一个时间轴的 jQuery 插件实现,你可以方便的使用它来生成一个动态的时间轴特效,提供了垂直和水平显示方式,并且支持自动播放。
Timelinr 插件介绍:
引入 jQuery 类库和插件类库,如下:
- <script src="js/jquery-1.6.1.min.js" type="text/javascript"></script>
- <script src="js/jquery.timelinr-0.9.js" type="text/javascript"></script>
初始化缺省参数,如下:
- <script type="text/javascript">
- $(function() {
- $().timelinr();
- });
- </script>
或者定制参数内容,如下:
- <script type="text/javascript">
- $(function() {
- $().timelinr({
- orientation: 'horizontal',
- // value: horizontal | vertical, default to horizontal
- containerDiv: '#timeline',
- // value: any HTML tag or #id, default to #timeline
- datesDiv: '#dates',
- // value: any HTML tag or #id, default to #dates
- datesSelectedClass: 'selected',
- // value: any class, default to selected
- datesSpeed: 500,
- // value: integer between 100 and 1000 (recommended), default to 500 (normal)
- issuesDiv: '#issues',
- // value: any HTML tag or #id, default to #issues
- issuesSelectedClass: 'selected',
- // value: any class, default to selected
- issuesSpeed: 200,
- // value: integer between 100 and 1000 (recommended), default to 200 (fast)
- issuesTransparency: 0.2,
- // value: integer between 0 and 1 (recommended), default to 0.2
- issuesTransparencySpeed: 500,
- // value: integer between 100 and 1000 (recommended), default to 500 (normal)
- prevButton: '#prev',
- // value: any HTML tag or #id, default to #prev
- nextButton: '#next',
- // value: any HTML tag or #id, default to #next
- arrowKeys: 'false',
- // value: true/false, default to false
- startAt: 1,
- // value: integer, default to 1 (first)
- autoPlay: 'false',
- // value: true | false, default to false
- autoPlayDirection: 'forward',
- // value: forward | backward, default to forward
- autoPlayPause: 2000
- // value: integer (1000 = 1 seg), default to 2000 (2segs)
- });
- });
- </script>
HTML 代码如下:
- <div id="timeline">
- <ul id="dates">
- <li><a href="#">date1</a></li>
- <li><a href="#">date2</a></li>
- </ul>
- <ul id="issues">
- <li id="date1">
- <p>Lorem ipsum.</p>
- </li>
- <li id="date2">
- <p>Lorem ipsum.</p>
- </li>
- </ul>
- <a href="#" id="next">+</a> <!-- optional -->
- <a href="#" id="prev">-</a> <!-- optional -->
- </div>
html 结构:
- <ul id="da-thumbs" class="da-thumbs">
- <li>
- <a href="#">
- <img src="images/list.jpg" />
- <div><span>简介</span></div>
- </a>
- </li>
- <li>
- <!-- ... -->
- </li>
- <!-- ... -->
- </ul>
代码构成,CSS 部分
- .da-thumbs li {
- float: left;
- margin: 5px;
- background: #fff;
- padding: 8px;
- position: relative;
- box-shadow: 0 1px 3px rgba(0,0,0,0.1);
- }
- .da-thumbs li a,
- .da-thumbs li a img {
- display: block;
- position: relative;
- }
- .da-thumbs li a {
- overflow: hidden;
- }
- .da-thumbs li a div {
- position: absolute;
- background: rgba(75,75,75,0.7);
- width: 100%;
- height: 100%;
- }
CSS 动画关键部分,采用 css3 的动画效果,以及添加方向的 class
- .da-thumbs li a div.da-animate {
- -webkit-transition: all 0.3s ease;
- -moz-transition: all 0.3s ease-in-out;
- -o-transition: all 0.3s ease-in-out;
- -ms-transition: all 0.3s ease-in-out;
- transition: all 0.3s ease-in-out;
- }
- /* 动画开始阶段的class */
- .da-slideFromTop {
- left: 0px;
- top: -100%;
- }
- .da-slideFromBottom {
- left: 0px;
- top: 100%;
- }
- .da-slideFromLeft {
- top: 0px;
- left: -100%;
- }
- .da-slideFromRight {
- top: 0px;
- left: 100%;
- }
- /* 动画结果阶段的class: */
- .da-slideTop {
- top: 0px;
- }
- .da-slideLeft {
- left: 0px;
- }
动画的 js 脚本部分
脚本部分,就是引入 jquery 文件,引入该插件。然后调用该插件即可。
- $(function() {
- $('#da-thumbs > li').hoverdir();
- });
该插件支持动画效果,延迟动画效果,和反向
- $('#da-thumbs > li').hoverdir({
- hoverDelay: 50,
- reverse: true
- });
注:hoverDelay 是延迟加载时间,越大时间越长。reverse 是是否反向,true 表示反向,默认 false。插件名 jquery.hoverdir.js
插件下载地址: https://pan.baidu.com/s/1pLaEo59 密码:rore
html 代码:
- <div>
- <input type="radio" name="rd" class="same" value='选项二' >选项一
- <input type="radio" name="rd" class="same" value='选项二'>选项二
- <input type="radio" name="rd" class="same others" value='其它'>其它
- <input type="text" name="txt" class="txt" value=""/>
- </div>
jquery 代码:
- $(function() {
- $(".same").click(function() {
- $(this).siblings().attr("checked", false);
- $(this).attr("checked", true);
- if ($(this).attr("class").indexOf('others') >= 0) {
- $(this).siblings('.txt').show();
- } else {
- $(".others").siblings('.txt').hide();
- }
- });
- })
注释: if 语句也可以使用 if($(this).hasClass("others")) 进行判断
实现效果如下:
看了网友的回复,确实 css 解决是最简单的,代码如下:
- .others ~ input[type='text'] {
- display:none;
- }
- .others:checked ~ input[type='text'] {
- display:inline;
- }
注:但是但是 IE9 以下低版本不支持。
实现整屏上下翻效果:
需加载的 js
- <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
- <script type="text/javascript" src="js/jquery.mousewheel.js"></script>
css 样式如下:
- body{padding:0;margin:0; overflow:hidden }
- ul{list-style:none;}
- .content{width:100%;height100%;position:relative;top:0;}
- .div_01,.div_02,.div_03,.div_04{width:100%;margin:0 auto; text-align: center;}
- .div_01{background: #b20909;}
- .div_02{background: #0941b2;}
- .div_03{background: #2db209;}
- .div_04{background: #b29c09;}
- .left_fixed{position:fixed;width:15px; height:100px; left:100px;top:200px;z-index:999;}
- .left_fixed ul li{
- background:#000;cursor:pointer;width:15px;height: 15px;
- border-radius:15px;margin-bottom: 10px;
- }
- .left_fixed ul li.active{background:#fff;}
jquery 代码如下:
- var page=0;//翻屏变量,初始第一屏
- var shakStaute = 0; //该变量作用是鼠标滑轮一直向下或者向上滑动时出现抖动现象
- $(function(){
- var starttime = 0,
- endtime = 0;
- $("body").mousewheel(function(event, delta) {
- starttime = new Date().getTime(); //记录翻屏的初始时间
- if (delta < 0&& page>=0 && page<=$(".content .divsame").length-2) {
- if (shakStaute>=0 &&(starttime == 0 || (endtime - starttime) <= -500)) { //在500ms内执行一次翻屏
- shakStaute=1;
- page++;
- renderPage(page,true); //翻屏函数
- endtime = new Date().getTime(); //记录翻屏的结束时间
- }
- } else if (delta>0 && page>=1 && shakStaute==1 && (starttime == 0 || (endtime - starttime) <= -500)) {
- page--;
- renderPage(page,true);
- endtime = new Date().getTime();
- }
- });
- var div_height=$(window).height();
- $(".divsame").css({'height':div_height});
- $(window).resize(function(){
- div_height=$(window).height();
- $(".divsame").css({'height':div_height});
- $('.content').animate({top:-page*div_height }, 100);
- });
- $(".left_fixed ul li").on("click", function(){ //点击小导航也执行翻屏
- var index = $(this).index();
- if(index>0){
- shakStaute==1;
- }
- page = index;
- renderPage(page, true);
- $(".left_fixed ul li").removeClass("active");
- $(this).addClass("active");
- return false;
- });
- function renderPage(pageNumber, isScroll){
- if (isScroll){
- $('.content').animate({top:-pageNumber*div_height }, 'slow');
- $(".left_fixed ul li").removeClass("active");
- $(".left_fixed ul li").eq(pageNumber).addClass("active");
- }
- return;
- }
- })
同时也是实时响应的。
插件下载地址: https://pan.baidu.com/s/1gfOZ9q7 密码:ocq3
头部需加载的:
- <script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
- <script src="js/TouchSlide.1.0.js" type="text/javascript"></script>
- <script src="js/popup.js" type="text/javascript"></script>
html 代码:
- <div class="tip_boxs" id="tip_boxs" style="display:none;">
- <div class="align">
- <div id="slideBoxindexb">
- <div class="bd">
- <ul class="clearfix">
- <li><img src="images/list_01.jpg" /></li>
- <li><img src="images/list_02.jpg" /></li>
- <li><img src="images/list_03.jpg" /></li>
- </ul>
- </div>
- <div class="hd">
- <span class="prev"></span>
- <span class="next"></span>
- </div>
- </div>
- <div class="pop_con close">
- <p class="time">2014-10-06</p>
- <h5>餐桌上的创意美学</h5>
- <p>Audi City Beijing是亚洲首家数字化奥迪展厅,坐落于市中心东方广场。Audi City Beijing是奥迪品牌为粉丝们创造的一个可以相识交流的奇幻场所,同时,Audi City Beijing为人们提供了一个与品牌交流对话的空间,让奥迪与城市生活更加紧密地联系在一起。</p>
- </div>
- </div>
- </div>
css 样式:
- /*弹框*/
- .tip_boxs{z-index:9999; width:80%; position:relative;left:10%;display:none;height:100%;display:-webkit-box; -webkit-box-pack: center;-webkit-box-align: center; text-align:center; margin:0 auto; }
- .tip_boxs .align{border-radius: 10px;overflow:hidden;width:100%;background: #fff;}
- .tip_boxs_zhezhao{ background:#000; opacity:0.8; z-index:8888; display:none; position:fixed; top:0; left:0;}
- #slideBoxindexb{ position:relative; width:100%; overflow:hidden; margin:0 auto;}
- #slideBoxindexb .bd{ position:relative; z-index:0; width:100%;}
- #slideBoxindexb .bd .tempWrap{width:100%;}
- #slideBoxindexb .bd li{ position:relative;float:left;}
- #slideBoxindexb .bd li{display: block;width:100%;display: -webkit-box;-webkit-box-pack: center;-webkit-box-align: center;}
- #slideBoxindexb .bd li img{display: block;width:100%;border-top-left-radius: 10px;border-top-right-radius: 10px;}
- #slideBoxindexb .prev,#slideBoxindexb .next{cursor:pointer; position:absolute;top:50%;margin-top:-16px;display:block; width:30px; height:32px;background: url(../images/prev_next_bg.png) no-repeat; }
- #slideBoxindexb .prev{left:5px;}
- #slideBoxindexb .next{right:5px;background-position: -30px 0;}
- .tip_boxs .pop_con{width:100%;padding:10px;box-sizing:border-box;background: #fff;font-size: 12px;color:#060505;text-align: left;}
- .tip_boxs .pop_con p{text-indent: 2em;line-height: 26px;}
- .tip_boxs .pop_con p.time{color:#000;text-indent:0;}
- .tip_boxs .pop_con h5{font-size: 14px;font-weight: bold;}
jquery 代码:
- <script type="text/javascript">
- $(function() {
- $(".content_02 .list_item li").on('click',
- function() {
- popup($(".tip_boxs"));
- TouchSlide({
- slideCell: "#slideBoxindexb",
- autoPlay: false,
- mainCell: ".bd ul",
- effect: "leftLoop"
- });
- })
- })
- </script>
实现效果图为:
注:其中 TouchSlide.1.0.js 为弹出层中图片预览左右滑动效果;popup.js 为弹框
分享一个 jQuery 的预加载插件,这个插件通过检查页面中的所有元素来提前加载所有包含的图片(包括背景图片),这个版本的插件是原来版本的一个更新,更容易使用。
Queryloader 目前需要 jQuery1.7,并且支持
。如何使用
- IE>7, Chrome, Safari和Firefox
引入类库
- <script src="js/jquery.queryloader2.js"type="text/javascript"></script>
当然你必须在以上代码之前引入 jQuery 类库,然后调用如下代码:
- $(document).ready(function() {
- $("body").queryLoader2();
- });
如果你在 iOS 上使用,请调用如下:
- window.addEventListener('DOMContentLoaded', function() {
- $("body").queryLoader2();
- });
相关选项:
下载地址: https://pan.baidu.com/s/1bpLJVGz 密码:rsgs
实现原理
首先,我们讲解一下放大镜效果的实现方式:
方法一:准备一张高像素的大图,当鼠标放到原图上,加载显示大图的对应位置。
方法二:对原图片进行放大,也就是调整原图的长和宽。
上面我们介绍了通过两种方式实现放大镜效果,接下来,我们将以上的两种方式应用到我们的 jQuery 插件中。
首先,我们需要一个 img 元素显示原图对象,还需要一个容器作为显示框;显示框里面存放大图对象。当鼠标移动到原图上时,通过对大图进行绝对定位来显示对应的部位,实现类似放大镜的效果。
接下来,让我们定义 Index.html 页面,具体实现如下:
- <!DOCTYPE html>
- <html>
- <head>
- <title>放大镜效果</title>
- <meta charset="utf-8"/>
- <meta name="description" content=""/>
- <meta name="keywords" content=""/>
- <link type="text/css" rel="stylesheet" href="css/reset.css"/>
- <link type="text/css" rel="stylesheet" href="css/main.css"/>
- <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
- <script type="text/javascript" src="js/jquery.imageZoom.js"></script>
- </head>
- <body>
- <div class="magnify">
- <div class="large"></div>
- <img class="small" src="images/iphone.jpg" width="200" />
- </div>
- <div class="magnify_02">
- <div class="large_02"></div>
- <img class="small_02" src="images/img5.jpg" width="400"/>
- </div>
- <script type="text/javascript">
- $(function(){
- $(".magnify").hover(function(){
- $.fn.imageZoom({
- small :"small",
- large : "large",
- magnify: "magnify"
- });
- },function(){})
- $(".magnify_02").hover(function(){
- $.fn.imageZoom({
- small : "small_02",
- large : "large_02",
- magnify: "magnify_02"
- });
- },function(){})
- })
- </script>
- </body>
- </html>
css 样式:
- .magnify {width: 200px; margin: 50px auto; position: relative;}
- .large {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
- .small { display: block; }
- .magnify_02 {width: 400px; margin: 50px auto; position: relative;}
- .large_02 {width: 175px; height: 175px;position: absolute;border-radius: 100%;z-index:99;box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);background: url('../images/iphone.jpg') no-repeat;display: none;}
- .small_02 { display: block; }
mousemove 事件
接下来,我们通过 jQuery 插件形式来实现放大镜效果,当鼠标移动到 small 对象上方时,就会在 large 对象中显示大图的对应位置,这就涉及到 mousemove 事件了,所以,我们需要实现 mousemove 事件的监听方法。
实现 jquery.imagezoom.js 插件:
- ; (function($) {
- $.fn.imageZoom = function(options) {
- var defaults = {
- scaling: 0.3,
- small: "small",
- large: "large",
- magnify: "magnify"
- };
- options = $.extend(defaults, options),
- native_width = 0,
- native_height = 0,
- current_width = 0,
- current_height = 0,
- magnify = "." + options.magnify;
- small = "." + options.small;
- $small = $(small);
- large = "." + options.large;
- $large = $(large);
- $(magnify).mousemove(function(e) {
- var image_object = new Image();
- image_object.src = $small.attr('src');
- if (!+ [1, ]) {
- native_height = image_object.height;
- native_width = image_object.width;
- } else {
- image_object.onload = function() {
- image_object.onload = null;
- native_height = image_object.height;
- native_width = image_object.width;
- }
- }
- current_height = $small.height();
- current_width = $small.width();
- var magnify_offset = $(this).offset();
- var mx = e.pageX - magnify_offset.left;
- var my = e.pageY - magnify_offset.top;
- if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
- $large.fadeIn(100);
- } else {
- $large.fadeOut(100);
- }
- if ($large.is(":visible")) {
- var rx = Math.round(mx / $small.width() * native_width - $large.width() / 2) * -1,
- ry = Math.round(my / $small.height() * native_height - $large.height() / 2) * -1,
- bgp = rx + "px " + ry + "px",
- px = mx - $large.width() / 2,
- py = my - $large.height() / 2;
- $large.css({
- left: px,
- top: py,
- backgroundPosition: bgp
- });
- }
- });
- };
- })(jQuery);
注释:当鼠标移动到 magnify 对象中,我们需要获取鼠标在 magnify 中的相对坐标位置,这里我们把相对坐标定义为 (mx,my),通过上图我们知道相对坐标等于。
- (pageX - offsetLeft, pageY - offsetTop)
现在,我们已经获取鼠标在 magnify 对象中的坐标值,接下来,需要获取对应大图的相应坐标,这里我们把大图的对应坐标定义为 (rx,ry),我们可以通过比例关系获取(rx,ry) 的值。
- mx / small.width (原图的宽)= rx / native_width(大图的宽)
- my / small.height (原图的长)= ry / native_height(大图的长)
通过上面的比例关系,我们知道大图的坐标 (rx,ry) 等于
。
- (mx/small.width*native_width, my/small.height*native_height)
mousewheel 事件
前面,我们通过 mousemove 事件来放大图片,这里我们将通过鼠标的滚轮事件实现图片放大效果。
由于,不同的浏览器有不同的滚轮事件。主要是有三种:
、
- onmousewheel(IE 6/7/8)
和 DOMMouseScroll(只有 Firefox 支持),关于这三个事件这里不做详细的介绍了。
- mousewheel(IE9,Chrome,Safari和Opera)
由于不同浏览器之间存在着差异,为了实现浏览器之间的兼容,所以,我们需要监听以上三种滚轮事件(onmousewheel,mousewheel 和 DOMMouseScroll),具体实现如下:
- $(".magnify").bind('DOMMouseScroll mousewheel onmousewheel',
- function(e) {});
上面,我们实现了兼容不同浏览器的滚轮事件监听方法,接下来,判断滚轮向上或向下也要考虑不同浏览器的兼容性,主流的览器(IE、Opera、Safari、Firefox、Chrome)中 Firefox 使用 detail,其余四类使用 wheelDelta;两者只在取值上不一致,代表含义一致,detail 与 wheelDelta 只各取两个值,detail 只取 ±3,wheelDelta 只取 ±120,其中正数表示为向上,负数表示向下。
由于 detail 和 wheelDelta 都有两个值表示向上或向下滚动,所以不同浏览器间可以通过以下方式实现兼容,具体实现如下:
- $(".magnify").bind('DOMMouseScroll mousewheel onmousewheel', function(e) {
- // cross-browser wheel delta
- var e = window.event || e; // old IE support.
- var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
- });
上面,我们已经处理了不同浏览器滚轮监听方法,当用户滚动滚轮时需要动态地修改原图的尺寸,这里我们定义缩放比 scaling 为 0.3,也就是说每当用户滚动一下滚轮原图就按 0.3 的比例进行缩放,具体实现如下:
- // Gets the image scaling height and width.
- native_height += (native_height * scaling * delta);
- native_width += (native_width * scaling * delta);
- // Update backgroud image size.
- $large.css('background-size', native_width + "px " + native_height + "px");
上面,我们实现了放大镜效果,当我们鼠标停留在图片上方会自动放大图片的相应部位,当然我们可以通过滚轮调整放大的比例。
参考
http://tech.pro/tutorial/681/css-tutorial-the-background-position-property
http://www.sitepoint.com/html5-javascript-mouse-wheel/
http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3
实现思路
js 代码
- ; (function($) {
- $.fn.snow = function(options) {
- var $flake = $('<div class="flake" />').css({
- 'position': 'absolute',
- 'top': '-50px'
- }),
- documentHeight = $(document).height(),
- documentWidth = $(document).width(),
- defaults = {
- flakeChar: "❄",
- minSize: 10,
- maxSize: 20,
- newOn: 500,
- flakeColor: '#ffffff',
- durationMillis: null
- },
- options = $.extend({},
- defaults, options);
- $flake.html(options.flakeChar);
- var interval = setInterval(function() {
- var startPositionLeft = Math.random() * documentWidth - 100,
- startOpacity = 0.5 + Math.random(),
- sizeFlake = options.minSize + Math.random() * options.maxSize,
- endPositionTop = documentHeight - defaults.maxSize - 40,
- endPositionLeft = startPositionLeft - 100 + Math.random() * 200,
- durationFall = documentHeight * 10 + Math.random() * 5000;
- $flake.clone().appendTo('body').css({
- left: startPositionLeft,
- opacity: startOpacity,
- 'font-size': sizeFlake,
- color: options.flakeColor
- }).animate({
- top: endPositionTop,
- left: endPositionLeft,
- opacity: 0.2
- },
- durationFall, 'linear',
- function() {
- $(this).remove()
- });
- },
- options.newOn);
- if (options.durationMillis) {
- setTimeout(function() {
- clearInterval(interval);
- },
- options.durationMillis);
- }
- };
- })(jQuery);
调用方式:
- $(function(){
- $("body").snow({'durationMillis':2000}); //2s后停止生成雪花
- })
参数解释:
- * @params flakeChar - 实现雪花图案的html字符
- * @params minSize - 雪花的最小尺寸
- * @params maxSize - 雪花的最大尺寸
- * @params newOn - 雪花出现的频率
- * @params flakeColors - 雪花颜色
- * @params durationMillis - 多少毫米后停止生成雪花
- * @example $.fn.snow({ maxSize: 200, newOn: 1000 });
实现效果如图所示:
实现原理:
- ('html, body').animate({ scrollTop:(hash).offset().top
- }, 800, function(){
- window.location.hash = hash;
- });
代码:
- <!DOCTYPE html>
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
- </script>
- <script>
- $(document).ready(function() {
- // Add smooth scrolling to all links
- $("a").on('click',
- function(event) {
- // Make sure this.hash has a value before overriding default behavior
- if (this.hash !== "") {
- // Prevent default anchor click behavior
- event.preventDefault();
- // Store hash
- var hash = this.hash;
- // Using jQuery's animate() method to add smooth page scroll
- // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
- $('html, body').animate({
- scrollTop: $(hash).offset().top
- },
- 800,
- function() {
- // Add hash (#) to URL when done scrolling (default click behavior)
- window.location.hash = hash;
- });
- } // End if
- });
- });
- </script>
- <style>
- body, html, .main { height: 100%; } section { min-height: 100%; }
- </style>
- </head>
- <body>
- <a href="#section2" style="
- font-size: 30px;
- font-weight: bold;
- text-align: center;
- ">
- 点击此处平滑滚动到第二部分
- </a>
- <div class="main">
- <section>
- </section>
- </div>
- <div class="main" id="section2">
- <section style="
- background-color: #03c03c;
- color: #fff;
- font-size: 30px;
- text-align: center">
- SECTION 2
- </section>
- </div>
- </body>
- </html>
jQuery 的动画方法(animate)支持各种属性的过渡,但是默认并不支持色彩的过渡,该插件正是来补足这一点!
PS: 该插件支持 RGBA 颜色的过渡,但是请注意,。
- IE8以下的版本不支持 RGBA 颜色
支持以下属性:
使用方法:
载入 JavaScript 文件, 首先页面中引入你的 JQ 版本,然后引入下面的插件代码:
- <script src='jquery.animate-colors.js'></script>
调用方式:
- $('#demodiv').animate({ color:'#E4D8B8' })
- $('#demodiv').animate({ backgroundColor:'#400101' })
- $('#demodiv').animate({ borderBottomColor:'#00346B' })
- $('#demodiv').animate({ borderColor:'#F2E2CE' })
- $('#demodiv').animate({ color:'rgba(42, 47, 76, 0.1)' })
下面贴一下不同的 jquery 版本,使用该插件的版本不一样,如下:
(适用于 jQuery 1.8 以上版本): 《下载地址》
- jQuery Animate colors
(适用于 jQuery 1.7.2 以下版本): 《下载地址》
- jQuery Animate colors
- (function($) {
- /**
- * Check whether the browser supports RGBA color mode.
- *
- * Author Mehdi Kabab <http://pioupioum.fr>
- * @return {boolean} True if the browser support RGBA. False otherwise.
- */
- function isRGBACapable() {
- var $script = $('script:first'),
- color = $script.css('color'),
- result = false;
- if (/^rgba/.test(color)) {
- result = true;
- } else {
- try {
- result = (color != $script.css('color', 'rgba(0, 0, 0, 0.5)').css('color'));
- $script.css('color', color);
- } catch(e) {}
- }
- return result;
- }
- $.extend(true, $, {
- support: {
- 'rgba': isRGBACapable()
- }
- });
- var properties = ['color', 'backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'outlineColor'];
- $.each(properties,
- function(i, property) {
- $.Tween.propHooks[property] = {
- get: function(tween) {
- return $(tween.elem).css(property);
- },
- set: function(tween) {
- var style = tween.elem.style;
- var p_begin = parseColor($(tween.elem).css(property));
- var p_end = parseColor(tween.end);
- tween.run = function(progress) {
- style[property] = calculateColor(p_begin, p_end, progress);
- }
- }
- }
- });
- // borderColor doesn't fit in standard fx.step above.
- $.Tween.propHooks.borderColor = {
- set: function(tween) {
- var style = tween.elem.style;
- var p_begin = [];
- var borders = properties.slice(2, 6); // All four border properties
- $.each(borders,
- function(i, property) {
- p_begin[property] = parseColor($(tween.elem).css(property));
- });
- var p_end = parseColor(tween.end);
- tween.run = function(progress) {
- $.each(borders,
- function(i, property) {
- style[property] = calculateColor(p_begin[property], p_end, progress);
- });
- }
- }
- }
- // Calculate an in-between color. Returns "#aabbcc"-like string.
- function calculateColor(begin, end, pos) {
- var color = 'rgb' + ($.support['rgba'] ? 'a': '') + '(' + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ',' + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ',' + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);
- if ($.support['rgba']) {
- color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
- }
- color += ')';
- return color;
- }
- // Parse an CSS-syntax color. Outputs an array [r, g, b]
- function parseColor(color) {
- var match, triplet;
- // Match #aabbcc
- if (match = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(color)) {
- triplet = [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16), 1];
- // Match #abc
- } else if (match = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(color)) {
- triplet = [parseInt(match[1], 16) * 17, parseInt(match[2], 16) * 17, parseInt(match[3], 16) * 17, 1];
- // Match rgb(n, n, n)
- } else if (match = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) {
- triplet = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), 1];
- } else if (match = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(color)) {
- triplet = [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10), parseFloat(match[4])];
- // No browser returns rgb(n%, n%, n%), so little reason to support this format.
- }
- return triplet;
- }
- })(jQuery);
官网地址: https://bitstorm.org/jquery/color-animation/
来源: https://segmentfault.com/a/1190000012605961