我从这个例子开始,并添加到代码中,使它:
- 动态高度
- 可访问的JS关闭
我做的对吗?这能在大多数浏览器上工作吗?
工作版本:
原始:$('#example-links a').hover(function(){
var index = $("#example-links a").index(this);
$('#example-content').animate({"marginTop" : -index*220 + "px"}); // multiply by height+top/bottom padding/margin/border
});
我修改的代码,与上面的代码相比,它看起来有点长:
var maxHeight = 0, container_maxHeight = 0;
var example_content = $("#example-content");
var example_div = example_content.children("div");
example_div.each(function() {
if($(this).height() > maxHeight) {
maxHeight = $(this).height();
container_maxHeight = $(this).outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").css({
"overflow":"hidden",
"height": container_maxHeight+"px"
});
$('#example-links a').bind('click mouseover', function(e){
var index = $("#example-links a").removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
我绑定了点击和鼠标悬停,因为我希望它通过鼠标悬停工作,但我也希望它在没有鼠标激活悬停的手机上浏览时工作。
一切似乎都很好,如果JS关闭,我唯一要添加的是节id,使其更易于访问。您可以在这里查看。
对于每个部分,您添加一个id到换行div,然后在您的侧链接中链接到该id。
我会把你的代码再清理一下:
(function($){
$(document).ready(function(){
var maxHeight = 0, container_maxHeight = 0,
example_content = $("#example-content"),
example_div = example_content.children("div");
example_div.each(function() {
var $section = $(this);
if($section.height() > maxHeight) {
maxHeight = $section.height();
container_maxHeight = $section.outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").height(container_maxHeight);
var $tabs = $('#example-links a');
$tabs.bind('click mouseover', function(e){
var index = $tabs.removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
});
})(jQuery);