Best way to do a horizontal scrolling pane in jQuery?
I came up with the solution below. It works great, but I'm curious to know if there's a more efficient way of doing it. Thanks!
HTML:
<div id="magic-pane" style="width: 300px; height: 400px; background: #eee; overflow: hidden">
<div id="scroller" style="width: 600px; height: 100%; left: 0px; position: relative">
开发者_JAVA百科 <div id="pane1" style="width: 300px; height: 100%; background: #efe; float: left">
<span id="pane1-clicker">Whee, click me!</span>
</div>
<div id="pane2" style="width: 300px; height: 100%; background: #fee; float: left">
<span id="pane2-clicker">Whoosh! Click me!</span>
</div>
</div>
</div>
Script:
$(document).ready(function() {
$('#pane1-clicker').click(function() {
$('#scroller').animate({ left: '-300px' }, 500);
});
$('#pane2-clicker').click(function() {
$('#scroller').animate({ left: '0' }, 500);
});
});
So basically, the magic-pane is a small viewport that's 300px wide. Inside it is a scroller that's twice as wide and contains two divs side-by-side. Pretty simple, but again, just wondering if there's a more efficient way of coding this.
Demo
When the number are minimum, you do not need to worry about anything. Like in you case, 2 is pretty manageable. Note: that you are writing separate onClick
function for all the pane, which will create problem.
But as the number grow, lets say 50, then you will have to write different onClick functions of $('#pane1-clicker')
.... $("#pane50-clicker)
, which is highly inefficient. You should modify your script, to support any number of panes, without writing extra codes.
- Also, extend the function, so that it can be used as plugin.
- It would be better if the plugin could match a particular selector and assign the related positions like
left:300px
From your current code, the only thing I'd probably change right off the bat is to take out the $('#scroller')
from the two click
handlers into a closure. That way, the handlers don't have to select it every single time a click occurs.
var $scroller = $('#scroller');
$('#pane1-clicker').click(function() {
$scroller.animate({ left: '-300px' }, 500);
});
$('#pane2-clicker').click(function() {
$scroller.animate({ left: '0' }, 500);
});
精彩评论