我希望通过我的网页上的内容罢工。一些内容是文本,另一些是链接,.而,我需要一个函数,可以直接通过它,。
找到了这个很好的答案:我如何通过使用JavaScript在一段文字上的效果动画一个打击? (第二个答案),但是我想把它转换成一个函数,这样我就可以在任何地方使用它了。
他最初的摇摆不定:http://jsfiddle.net/alexdickson/wmBYx/
这是他的JS:
var findText = function(element, pattern, callback) {
if ( ! element.childNodes) {
return;
}
for (var childi = element.childNodes.length; childi-- > 0;) {
var child = element.childNodes[childi];
if (child.nodeType == 1) {
findText(child, pattern, callback);
} else if (child.nodeType == 3) {
var matches = [];
var match;
while (match = pattern.exec(child.data))
matches.push(match);
for (var i = matches.length; i-- > 0;)
callback.call(window, child, matches[i]);
}
}
}
findText(document.body, /./g, function(node, match) {
var element = document.createElement('span');
node.splitText(match.index + 1);
element.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(element, node.nextSibling);
});
var spans = document.getElementsByTagName('span'),
spansLength = spans.length,
currentSpan = 0,
interval = setInterval(function() {
if (currentSpan == spansLength) {
clearInterval(interval);
}
spans[currentSpan++].style.textDecoration = 'line-through';
}, 100); 说实话,我一点也不懂,所以我不知道如何把它转换成干函数。(我甚至不给你看我到目前为止的成绩,我很惭愧)。
谢谢你的帮忙
PS:我正在使用jquery,所以非常欢迎您在其中添加一些。
发布于 2012-09-06 02:31:17
您可以为它创建一个jQuery插件:
$.fn.strikeThrough = (function() {
var findText = function(element, pattern, callback) {
if ( ! element.childNodes) {
return;
}
for (var childi = element.childNodes.length; childi-- > 0;) {
var child = element.childNodes[childi];
if (child.nodeType == 1) {
findText(child, pattern, callback);
} else if (child.nodeType == 3) {
var matches = [];
var match;
while (match = pattern.exec(child.data))
matches.push(match);
for (var i = matches.length; i-- > 0;)
callback.call(window, child, matches[i]);
}
}
}
return function(pattern) {
pattern = pattern || /./g;
if (this.length > 1) {
this.each(function() {
$(this).strikeThrough(pattern);
});
return this;
}
findText(document.body, pattern, function(node, match) {
var element = document.createElement('span');
node.splitText(match.index + 1);
element.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(element, node.nextSibling);
});
var spans = this[0].getElementsByTagName('span'),
spansLength = spans.length,
currentSpan = 0,
interval = setInterval(function() {
if (currentSpan == spansLength) {
clearInterval(interval);
return;
}
spans[currentSpan++].style.textDecoration = 'line-through';
}, 100);
return this;
};
})();
$(function() {
$('div').strikeThrough();
});HTML:
<div>strike me out please but <strong>don't</strong> drop my events!</div>演示
发布于 2012-09-06 02:19:42
这太简单了。
$(function(){
//pass over the jQuery object.
strikeThrough($('.ele'));
});
/*
* Create function outside of .ready() scope
*/
function strikeThrough(ele){
ele.css('textDecoration', 'line-through');
}下面是工作的jsFiddle示例。
https://stackoverflow.com/questions/12292089
复制相似问题