我希望在我的网页上浏览内容。一些内容是文本,另一些是链接,......和我需要一个可以通过它实现的功能。
找到了这个很棒的答案:How do I animate a strike through effect using JavaScript on a piece of text?(第二个答案) 但是我想将它转换成一个函数,以便我可以在任何地方使用它。
他原来的jsfiddle: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);
说实话,我不明白任何一个,所以我不知道如何将其转化为DRY功能。 (甚至不会告诉你到目前为止我得到了什么,我感到很惭愧)。
感谢您的帮助
PS:我正在使用jquery,所以非常欢迎你加入一些。
答案 0 :(得分:6)
您可以为它创建一个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>
答案 1 :(得分:-2)
这非常简单。
$(function(){
//pass over the jQuery object.
strikeThrough($('.ele'));
});
/*
* Create function outside of .ready() scope
*/
function strikeThrough(ele){
ele.css('textDecoration', 'line-through');
}