【发布时间】:2014-04-10 08:57:00
【问题描述】:
我正在制作一个基本的 jQuery 插件,用户可以使用它来更改背景颜色、字体颜色等。
我希望插件的用户能够定义这些更改生效的元素。
我知道我必须使用“this”,但我不知道该怎么做。
这是插件的代码
(function($, window, document, undefined){
//Define your own variables first
var wrapper = $('.wrapper');
var p = $('p');
//Define the default settings here
var settings = {
textColor: 'red'
};
//Write your methods here
var methods = {
//Call this method to initialize the plugin
init: function(){
console.log("Initialize the plugin");
$('input').on('change', methods.changeColor);
$('select').on('change', methods.changeFont);
$('.slider').on('change', methods.changeWidth);
},
changeColor: function(){
console.log("This will change the background and/or font color");
var userBackgroundColor = $("#userBackgroundColor").val();
var userTextColor = $("#userTextColor").val().toLocaleLowerCase();
wrapper.css({
backgroundColor: userBackgroundColor,
color: userTextColor
});
},
changeFont: function(){
console.log("This will change the font");
var userFontSize = $("option:selected").val();
console.log(userFontSize);
p.css({
fontSize: userFontSize + 'em'
})
},
changeWidth: function(){
var p = $('p');
var userWidth = $(".slider").val();
var widthFontChange = userWidth / 20;
if (widthFontChange == 1) {
p.css({
width: userWidth + '%',
fontSize: widthFontChange + 'em'
});
}
else {
widthFontChange = userWidth / 2;
p.css({
width: userWidth + '%',
fontSize: widthFontChange + 'px'
})
}
}
};
//Actual plugin call
$.fn.pluginName = function(options){
//If the user overrides defaults by setting his own options
if(options){
settings = $.extend(settings, options);
}
//Put any eventHandlers here, like this:
this.on('change', methods.changeColor);
this.on('change', methods.changeFont);
this.on('change', methods.changeWidth);
//Init the plugin with the $selector
methods.init(this);
//Return this for jQuery chaining
return this;
};
}(jQuery, window, document));
这是用户可以在其中定义插件必须工作的对象的文件
$(document).ready(function(){
$('body').pluginName();
});
我的问题是,如何按照我想要的方式进行这项工作?
【问题讨论】:
-
我需要一些实用的东西来展示一个工作示例。你能举例说明你想如何使用这个插件吗?从这个基本的 JSFiddle jsfiddle.net/CgGjq 开始,填写一些 HTML 内容和一些您希望它执行的操作示例。
-
做到了。所以我想做的就是这个。当您滑动滑块时,p 文本会改变大小。但我想让插件用户有机会将其更改为例如 h1。
-
哦,对不起。以前从未使用过 JSFiddle ;) 这是新链接。我希望。 jsfiddle.net/CgGjq/2
-
我在下面给出了一个简单的答案,但是您当前的插件不能跨多个元素使用。全局选择器有太多的硬连线(如
.wrapper和段落p)。这些也需要成为插件的属性(将它们放在选项中)。 -
整个插件需要是一个对象,而不仅仅是静态方法。然后,您可以将
$element和options存储为this的属性以及目标元素的提供者选择器。使用当前的代码样式,您只能在页面上拥有其中一个。
标签: javascript jquery plugins jquery-plugins