以下是 jQuery将元素固定在容器中代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery将元素固定在容器中代码 </title>
<!--<link href='http://fonts.useso.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>-->
<link rel="stylesheet" type="text/css" href="css/bootstrap-ltr.min.css">
<link rel="stylesheet" type="text/css" href="css/default.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container" id="pinBoxContainer">
<div class="col-sm-3">
<div class="block-1 center">
<h2 class="headColor">Events</h2><br>
<div id="callbacks">
<span>current :</span> <span class="callback" id="pinBoxCurrent">0</span><hr>
<span>direction :</span> <span class="callback" id="pinBoxDirection">down</span><hr>
<span>width :</span> <span class="callback" id="pinBoxWidth">width</span><hr>
<span>active :</span> <span class="callback" id="pinBoxActive">false</span><hr>
<span>disabled :</span> <span class="callback" id="pinBoxDisabled">false</span><hr>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="block-2">
<!-- step 1 -->
<h1 id="how-to-use">How To Use</h1>
<h2 class="headColor">1. Load jQuery and include pinBox plugin file</h2>
<p>To use pinBox, you’ll need to make sure both the pinBox and jQuery 1.7 or higher scripts are included.</p>
<pre class="pre-show prettyprint linenums">
<!-- jQuery -->
<script src="jquery-1.9.1.min.js"></script>
<!-- Include pinBox plugin -->
<script src="js/jquery.pinBox.min.js"></script>
</pre>
<!-- step 2 -->
<h2 class="headColor">2. Set up your HTML</h2>
<p>You don't need any special markup. All you need is to wrap your divs inside the container for example #pinBoxContainer and add class to your div for example .pinBox .
read the code comments.</p>
<pre class="pre-show prettyprint linenums">
<!-- container with id -->
<div class="container" id="pinBoxContainer">
<!-- if you don't use bootstrap.css
make sure to add [position:relative]
if div parent have float property. -->
<div class="col-sm-4">
<!-- box you want to pin inside [id="pinBoxContainer"] have class or id -->
<div class="pinBox">
<h2 class="headColor">Example box</h2>
<p>some text</p>
</div>
</div>
<div class="col-sm-8">
<h2 class="headColor">Example box</h2>
<p>some text</p>
</div>
</div>
</pre>
<!-- step 3 -->
<h2 class="headColor">3. Call the plugin</h2>
<p>To make a pinned element stay within an outer container, use the Container option</p>
<pre class="pre-show prettyprint linenums">
$(document).ready(function() {
$(".pinBox").pinBox({
Top : '50px',
Container : '#pinBoxContainer',
});
});
</pre>
<!-- options -->
<h2 class="headColor" id="options">Call the plugin with options</h2>
<pre class="pre-show prettyprint linenums">
$(document).ready(function() {
$(".pinBox").pinBox({
//default 0px
Top : '50px',
//default '.container'
Container : '#pinBoxContainer',
//default 20
ZIndex : 20,
//default '767px' if you disable pinBox in mobile or tablet
MinWidth : '767px',
//events if scrolled or window resized
Events : function(e){
console.log(e);
// e.current => current scroll top [number]
// e.direction => scroll down or up [up,down]
// e.width => window width [number]
// e.active => if pinBox active [true,false]
// e.disabled => if window width < MinWidth pinBox will disabled [true, false]
}
});
});
</pre>
<!-- end -->
</div>
</div>
<div class="col-sm-3">
<div class="block-3 center">
<h2 class="headColor">Example box</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident</p>
</div>
</div>
</div>
<script src="js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="js/prettify.js"></script>
<script type="text/javascript" src="js/jquery.pinBox.min.js"></script>
<script type="text/javascript">
//scroll to div
jQuery.fn.scrollTo = function(elem, speed, top) {
if(top){
top = ($(elem).offset().top - top) ;
}else{
top = $(elem).offset().top;
}
$(this).animate({
// scrollTop: $(this).scrollTop() - $(this).offset().top + top
scrollTop: $(this).offset().top + top
}, speed == undefined ? 1000 : speed);
return this;
};
$(document).ready(function() {
window.prettyPrint && prettyPrint();
$('.menu a').click( function (e){
var eid = $(this).attr('href');
if($(eid).length){
e.preventDefault();
$("html,body").scrollTo(eid, 500,50);
}
});
var current, direction, width, active, disabled;
$('.block-1').pinBox({
Top:'20px',
Container : '#pinBoxContainer',
Events : function(e){
$('#pinBoxCurrent').text(e.current);
$('#pinBoxDirection').text(e.direction);
$('#pinBoxWidth').text(e.width);
$('#pinBoxActive').text(e.active);
$('#pinBoxDisabled').text(e.disabled);
if(current !== e.current){
uc('#pinBoxCurrent');
current = e.current;
}
if(direction !== e.direction){
uc('#pinBoxDirection');
direction = e.direction;
}
if(width !== e.width){
uc('#pinBoxWidth');
width = e.width;
}
if(active !== e.active){
uc('#pinBoxActive');
active = e.active;
}
if(disabled !== e.disabled){
uc('#pinBoxDisabled');
disabled = e.disabled;
}
}
});
$('.block-3').pinBox({Top:'20px', Container : '#pinBoxContainer'});
//update events class
function uc(e){
$(e).addClass('active');
setTimeout(function() {
$(e).removeClass('active');
}, 500);
}
});
</script>
</body>
</html>
JS代码(jquery.pinBox.min.js):
"function"!=typeof Object.create&&(Object.create=function(t){
"use strict";
function i(){
}
return i.prototype=t,new i}
),function(t,i,n,e){
"use strict";
var o={
Scroll:{
}
,Window:{
}
,init:function(i,n,e){
this.opt=t.extend({
}
,t.fn.pinBox.defaults,n),this.elem=i,this.Prepare(i),this.OnScroll(i),this.OnResize(i);
var o=this;
setTimeout(function(){
for(var t=e.length-1;
t>=0;
t--)o.fixContainerHeight(e[t])}
,1e3)}
,Prepare:function(i){
var n=t(i),e={
}
,o={
}
,a={
}
,r=this.ExtractData(n),s=r.pinBoxOptions||this.opt||{
}
;
if(s.Disabled===!1){
n.parent().is(".pinBox-wrapper")||(n.wrap("<div class='pinBox-wrapper'>"),n.parent().css({
position:"relative"}
));
var p=n.closest(s.Container),d=p.offset();
e.top=d.top,e.left=d.left,e.width=p.width(),e.height=p.height();
var l=n.offsetParent().offset();
o.top=l.top,o.left=l.left,n.parent().css("height",n.outerHeight()),a.width=n.outerWidth(),a.position="fixed",a.left=parseFloat(o.left),a.top=s.Top,a["z-index"]=s.ZIndex,n.data("pinBox",JSON.stringify(a)).data("pinBoxOptions",JSON.stringify(s)).data("pinBoxParent",JSON.stringify(o)).data("pinBoxContainer",JSON.stringify(e))}
}
,ExtractData:function(t){
var i={
}
,n=t.data("pinBox")||{
}
,e=t.data("pinBoxOptions")||{
}
,o=t.data("pinBoxParent")||{
}
,a=t.data("pinBoxContainer")||{
}
;
return"string"==typeof n&&(i.pinBox=JSON.parse(n)),"string"==typeof e&&(i.pinBoxOptions=JSON.parse(e)),"string"==typeof o&&(i.pinBoxParent=JSON.parse(o)),"string"==typeof a&&(i.pinBoxContainer=JSON.parse(a)),i}
,OnScroll:function(n){
var e=this;
t(i).scroll(function(){
var o=t(n),a=t(this).scrollTop(),r=e.ExtractData(o),s=r.pinBox,p=r.pinBoxOptions,d=r.pinBoxParent,l=r.pinBoxContainer;
if(e.Scroll.direction=a>e.Scroll.current?"down":"up",e.Scroll.current=a,e.Window.width=i.innerWidth||t(i).width(),a>l.top-parseInt(p.Top)&&e.Window.width>parseInt(p.MinWidth)){
p.Disabled=!1;
var c=o.closest(p.Container).height()-o.outerHeight(),h=(d.top||l.top)+c-parseInt(p.Top);
a>h?o.attr("style","").css({
width:s.width,position:"absolute",top:c}
):o.css(s),e.CallEvents(o,!0,p.Disabled)}
else e.Window.width<=parseInt(p.MinWidth)?p.Disabled===!1&&(o.attr("style","").unwrap(".pinBox-wrapper"),p.Disabled=!0):o.attr("style","").css({
width:s.width}
),e.CallEvents(o,!1,p.Disabled);
o.data("pinBoxOptions",JSON.stringify(p))}
)}
,OnResize:function(n){
var e=this,o=t(n);
t(i).resize(function(){
var a=e.ExtractData(o),r=a.pinBoxOptions;
if(e.Window.width=i.innerWidth||t(i).width(),r.Disabled=e.Window.width>parseInt(r.MinWidth)?!1:!0,r.Disabled===!1){
var s=o.parent().width();
o.attr("style","").css({
width:s}
)}
else o.attr("style","");
o.data("pinBoxOptions",JSON.stringify(r)),e.Prepare(n),e.CallEvents(o,!0,r.Disabled)}
)}
,CallEvents:function(t,i,n){
var e=this;
i?t.addClass("active"):t.removeClass("active"),"function"==typeof e.opt.Events&&e.opt.Events.call(t,{
current:e.Scroll.current,direction:e.Scroll.direction,width:e.Window.width,active:i,disabled:n}
)}
,fixContainerHeight:function(n){
var e=this,o=t(n),a=e.ExtractData(o),r=a.pinBoxOptions,s=a.pinBoxParent,p=a.pinBoxContainer,d=t(i).scrollTop(),l=o.closest(r.Container).height()-o.outerHeight(),c=(s.top||p.top)+l-parseInt(r.Top);
d>c&&o.attr("style","").css({
width:a.pinBox.width,position:"absolute",top:l,transition:".3s"}
)}
}
;
t.fn.pinBox=function(t){
var i=[],n=Object.create(o);
this.each(function(){
i.push(this),n.init(this,t,i)}
)}
,t.fn.pinBox.defaults={
Container:".container",Top:0,ZIndex:20,MinWidth:"767px",Events:!1,Disabled:!1}
}
(jQuery,window,document);
CSS代码(style.css):
body{font-family:"Montserrat","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:16px;line-height:22px;color:#6C7E92;/* Permalink - use to edit and share this gradient:http://colorzilla.com/gradient-editor/#1bbb9b+0,53839a+100 */
background:#1bbb9b;/* Old browsers */
background:-moz-linear-gradient(top,#1bbb9b 0%,#53839a 100%);/* FF3.6-15 */
background:-webkit-linear-gradient(top,#1bbb9b 0%,#53839a 100%);/* Chrome10-25,Safari5.1-6 */
background:linear-gradient(to bottom,#1bbb9b 0%,#53839a 100%);/* W3C,IE10+,FF16+,Chrome26+,Opera12+,Safari7+ */
filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#1bbb9b',endColorstr='#53839a',GradientType=0 );/* IE6-9 */
}
header{margin-bottom:50px;text-align:center;background-color:#2d343c;padding-bottom:50px;}
header h1{margin-top:50px;}
.block-1{height:500px;}
.block-1,.block-2,.block-3{padding:15px;border-radius:3px;background:#2D343C;border-bottom:2px solid #1C2025;box-shadow:0 0 2px 0 #069EE6;position:relative;}
.block-2{padding:15px 20px;}
.center{text-align:center;margin:auto;}
hr{margin:10px 0;border-top:1px solid #252B31;}
h1,.h1{font-size:30px;}
h2,.h2{font-size:24px;}
h1,.h1,h2,.h2,h3,.h3{margin:15px 0;}
h1 span{font-size:14px;}
nav{background:#313942;position:relative;border-bottom:1px solid #3c4650;}
.menu li{float:left;height:50px;margin:0 15px;list-style:none;}
.menu li a{line-height:50px;padding:0 30px;color:#9caea8;}
.headColor{color:#1bbb9b;}
#callbacks{text-align:left;padding:0 20px;}
.callback{background:#252B31;padding:5px 10px;line-height:16px;font-size:13px;border-radius:4px;transition:background .4s ease;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:80px;}
.callback.active{background:#1bbb9b;color:#222;}
@media screen and (max-width:767px){[class*="col-"]{margin-bottom:30px;}
}
.me{margin:150px 0;text-align:center;color:#ccc;}
.me a{display:block;width:120px;height:120px;margin:auto;border-radius:50%;overflow:hidden;border:5px solid #ccc;}
.me a img{width:100%;height:100%;}
/*******************************************************/
.com{color:#93a1a1;}
.lit{color:#195f91;}
.pun,.opn,.clo{color:#93a1a1;}
.fun{color:#dc322f;}
.str,.atv{color:#a3be8c;}
.kwd,.prettyprint .tag{color:#bf616a;}
.typ,.atn,.dec,.var{color:#d08770;}
.pln{color:#C1C1C1;}
.pun{color:#7791A5;}
pre.prettyprint{background-color:#252B31;border:0px solid #e1e1e8;tab-size:4;-moz-tab-size:4;-o-tab-size:4;-webkit-tab-size:4;}
/* Specify class=linenums on a pre to get line numbering */
ol.linenums{margin:0;/* IE indents via margin-left */
}
ol.linenums li{padding-left:12px;color:#bebec5;line-height:20px;text-shadow:0 1px 0 #222;}
@media screen and (max-width:400px){pre.prettyprint{-moz-tab-size:2;-o-tab-size:2;-webkit-tab-size:2;tab-size:2;padding-left:0;}
ol.linenums li{padding-left:0;}
}