【发布时间】:2014-07-15 22:37:12
【问题描述】:
我搜索并找到了 this question、that question 和 the other question,虽然它们很接近,但似乎没有什么能与我的问题相匹配。
我正在尝试将this answer 转为插件,而这不是first time I got stuck。
问题
我正在尝试创建一个 jQuery 插件,它用跨度包装每个字母,然后使用随机颜色和字体大小对其进行样式设置。该插件应该在悬停或单击时工作。页面首次加载时,没有错误。悬停或单击时,会出现错误“Uncaught TypeError: Cannot use 'in' operator to search...”。
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>
jQuery
;(function ($) {
$.fn.randomLetterStyles = function( options ) {
var settings = $.extend({
colors: ["#ddd", "#333", "#999", "#bbb"],
sizes:["12"],
type:"hover",
defaultColor: "#999",
defaultSize: "12"
}, options );
if(settings.type == "hover") {
$(this).hover(function(){
wrapLetters(this);
$('.random-styles', this).css('color', randomColor());
$('.random-styles', this).css('font-size', randomSize());
}, function(){
$('.random-styles', this).css({'color':settings.defaultColor, 'font-size':settings.defaultSize});
});
}
else if(settings.type == "click") {
$(this).on("click", function() {
wrapLetters(this);
$('.random-styles', this).css('color', randomColor());
$('.random-styles', this).css('font-size', randomSize());
});
}
else {
return "Invalid Type";
}
};
//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);
});
}
function randomColor() {
var index = Math.floor(Math.random() * settings.colors.length);
return settings.colors[index];
}
function randomSize() {
var index = Math.floor(Math.random() * settings.sizes.length);
return settings.sizes[index];
}
} ( jQuery ));
$(document).ready(function () {
$("#firstBox").randomLetterStyles();
$("#secondBox").randomLetterStyles({type:"click"});
$("#thirdBox").randomLetterStyles();
});
如果有帮助,我有 this fiddle 可以玩。
【问题讨论】:
标签: jquery