同事找帮忙需要写一个普通的焦点图,切换效果是渐变,默认不自动切换,图片有小点,点击小点可以切换图片。花了三个多小时写好,贴出来的目的是让那些开发jQuery插件的童鞋做个参考。
源码
focus.js
(function($) {
$.fn.focus = function(param){
var height = param.height || 200;
var width = param.width || 100;
var _this = null;
$(this).each(function(){
_this = $(this);
$('body').css({margin: 0, padding: 0});
_this.css({
width: width + 'px',
height: height+'px',
position: 'relative',
padding: 0
});
var fock_png_width = 16;
var fock_png_margin_sx = 8;
var ul_height = fock_png_width + fock_png_margin_sx * 2;
var box_height = _this.height();
var box_width = _this.width();
var fock_png_margin_zy = 10;
var js = document.scripts;
var speed = 500;
var sper_url = '';
var sper_file_name = 'sper.png';
var last_index = 0;
var lock = false;
var objImg = _this.find('>img');
if (objImg.length === 0) {
return false;
}else{
var img_length = objImg.length;
}
for (var i = js.length; i>0; i--) {
if (js[i-1].src.indexOf('lee_plug')>-1) {
sper_url = js[i-1].src.substring(0, js[i-1].src.lastIndexOf("/") + 1) + sper_file_name;
}
}
_this.append('<div style="position:absolute;top:'+(height-ul_height)+'px;background:#000;opacity:0.7;height:'+ul_height+'px;margin:0 auto;padding:0;width:100%;"></div>');
var html = '<ul style="position:absolute;top:'+(height-ul_height)+'px;height:'+ul_height+'px;margin:0 auto;padding:0;width:100%;opacity:0.7;">';
for (var i=0; i < img_length; i++) {
$(objImg[i]).css({
width: '100%',
height: '100%',
position: 'absolute',
margin: 0,
padding: 0
});
if (i >= 1) {
$(objImg[i]).hide();
var sper_weizhi = 0;
}else{
var sper_weizhi = '-' + fock_png_width + 'px';
}
var left = parseInt((box_width - img_length*(fock_png_width+fock_png_margin_zy*2)) /2) + i*(fock_png_width+fock_png_margin_zy);
html += '<li style="display:block;position:absolute;width:'+fock_png_width+'px;height:'+fock_png_width+'px;background:url('+sper_url+') 0 '+sper_weizhi+' no-repeat;margin:0; padding:0;cursor:pointer; top:'+parseInt((ul_height-fock_png_width)/2)+'px;left:'+left+'px;"></li>';
}
html += '</ul>';
_this.append(html);
_this.find('>ul>li').each(function(i){
$(this).get(0).onclick = function (num, obj) {
return function(){
if (num === last_index || lock) {
return false;
}
lock = true;
obj.find('>ul>li').each(function (i) {
$(this).css('background', 'url(' + sper_url + ') 0 0 no-repeat');
});
obj.find('>ul>li:eq(' + num + ')').css('background','url(' + sper_url + ') 0 -' + fock_png_width + 'px no-repeat');
obj.find('>img:visible').fadeOut(speed);
obj.find('>img:eq(' + num + ')').fadeIn(speed, function () {
lock = false;
last_index = num;
});
}
}(i, _this);
});
});
};
})(jQuery);
...