简单的jquery幻灯片脚本 – 我的jquery语法有问题吗?
var j$ = jQuery.noConflict();
j$(document).ready(function(){
j$.fn.slideShow = function(timeOut){
var $slidecontainer = this;
this.children(':gt(0)').hide();
setInterval(function() {
$slidecontainer.children().eq(0).fadeOut(2000).next().fadeIn(2000).addClass('on').nextAll().removeClass('on').end().appendTo($slidecontainer);}, timeOut || 1000);
var imgheight = this.children('.on').outerHeight();
this.css('height', imgheight );
};
j$(function() {
j$('.slideshow').slideShow(7000);});
});
在大多数情况下,上述脚本运行良好。 唯一的问题是图像高度的css没有应用于父容器。 当我在浏览器控制台中尝试此function时,它可以完美运行 当我在页面中调用脚本时,它不会应用图像高度。 它做了其他一切。
这是html
结果certificate以下是答案:
var j$ = jQuery.noConflict(); j$.fn.slideShow = function (timeOut) { var $slidecontainer = this; $slidecontainer.children(':gt(0)').hide(); setInterval(function () { $slidecontainer.children().eq(0).fadeOut(2000).next().fadeIn(2000).addClass('on').nextAll().removeClass('on').end().end().appendTo($slidecontainer); }, timeOut || 1000); var imgheight = $slidecontainer.children('img').first().outerHeight(); $slidecontainer.css('height', imgheight); }; j$(window).load(function () { j$('.slideshow').slideShow(7000); });
尝试,
var j$ = jQuery.noConflict(); j$.fn.slideShow = function (timeOut) { var $slidecontainer = this; this.children(':gt(0)').hide(); setInterval(function () { $slidecontainer.children().eq(0).fadeOut(2000).next().fadeIn(2000).addClass('on').nextAll().removeClass('on').end().end().appendTo($slidecontainer); }, timeOut || 1000); var imgheight = this.children('img').first().outerHeight(); this.css('height', imgheight); }; j$(window).load(function () { j$(function () { j$('.slideshow').slideShow(7000); }); });
$(window).load确保加载图像,这样它们的高度计算在所有浏览器中都可以正常运行。 您还可以专门查找每个img元素。
看起来你错过了一端(),你选择了next()然后选择了nextAl(),所以你需要两个end()来选择回到当前元素。
更新小提琴
你正在使用this
,而不是使用$slidecontainer
或$(this)
您已将此分配给$ slidecontainer变量。