我正在将这个问题的答案纺到jQuery插件中,但是我遇到了问题。我在.on()中使用变量作为事件,但是监听器从不触发。
jQuery的
(function ($) {
$.fn.randomLetterStyles = function( options ) {
var settings = $.extend({
colors: ["#ddd", "#333", "#999", "#bbb"],
sizes:["12"],
type:"hover",
defaultColor: "#999",
defaultSize: "12"
}, options );
//both of these appear in console
console.log("check 1");
console.log(settings.type);
$(this).on(settings.type, function() {
//this does not appear in console
console.log("check 2");
wrapLetters(this);
$('.random-styles', this).css('color', function(){
var idx = Math.floor(Math.random() * settings.colors.length);
return settings.colors[idx];
});
$('.random-styles', this).css('color', function(){
var idx = Math.floor(Math.random() * settings.sizes.length);
return settings.sizes[idx];
});
$('.random-styles', this).css('font-size', function(){
var idx = Math.floor(Math.random() * settings.sizes.length);
return settings.sizes[idx];
});
}, function(){
$('.random-styles', this).css({'color':settings.defaultColor, 'font-size':settings.defaultSize});
});
};
//Recursive function by Logan Smyth
// Wrap every letter in a <span> with .random-color class.
function wrapLetters(el){
if ($(el).hasClass('random-styles')) return;
// Go through children, need to make it an array because we modify
// childNodes inside the loop and things get confused by that.
$.each($.makeArray(el.childNodes), function(i, node){
// Recursively wrap things that aren't text.
if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);
// Create new spans for every letter.
$.each(node.data, function(j, letter){
var span = $('<span class="random-styles">').text(letter);
node.parentElement.insertBefore(span[0], node);
});
// Remove old non-wrapped text.
node.parentElement.removeChild(node);
});
}
} ( jQuery ));
$(document).ready(function() {
$("#firstBox").randomLetterStyles();
$("#secondBox").randomLetterStyles();
$("#thirdBox").randomLetterStyles();
});
的HTML
<div id="firstBox">This box works on hover!</div>
<div id="secondBox">This box works on click!</div>
<div id="thirdBox">This box has custom settings!</div>
的小提琴。
.on('hover', function)
不像.hover(function, function)
-它不接受两个功能。删除第二个事件,然后触发事件。
您仍然可以创建这两个事件
$("#firstBox").randomLetterStyles({type: 'mouseover', ...}).randomLetterStyles({type: 'mouseout', ...});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句