我喜欢这个<div class='error_message'> message </div>
。此<div>
没有特定的width
,具体取决于其文字。应该指出的是,它的文本始终不一样,有时会发生变化。所以我希望在延迟后根据元素中的字符数隐藏它。
我可以像这样持续延迟:(例如)
$("element").delay(5000).hide(200);
但我需要动态延迟时间。我希望隐藏包含短消息的<element>
比包含长消息的<element>
更快。
例如:
// hide after 1 sec
<div class='error_message'> message </div>
// hide after 2 sec
<div class='error_message'> message message </div>
// hide after 3 sec
<div class='error_message'> message message message </div>
等等......
有没有解决方法呢?
答案 0 :(得分:2)
function countWords(string) {
var ret = 0;
string.replace(/(\b+)/g, function(a) { ret++; });
return ret;
}
var len = 1000*countWords($(element).text());
$(element).delay(len).hide(200);
我怀疑这些方面的东西?
答案 1 :(得分:1)
怎么样:
$("element").each(function(){
var delay = $(this).html().length * 2;
$(this).delay(delay).hide(200);
});
答案 2 :(得分:1)
虽然您已经接受了答案,但我认为我提供了使用纯JavaScript的替代解决方案 - 如果只是为了完成感,因为您标记了问题javascript - 所以,一种可能性如下:
function wordDependentFadeOut (el) {
// retrieving the textContent of the supplied Node ('el'),
// trimming that textContent to remove leading/trailing white-space,
// splitting the resulting string by any remaining white-space (between words)
// to produce an array of individual words,
// finding the length of the resulting array and concatenating the 's' character:
var delayInSeconds = el.textContent.trim().split(/\s+/).length + 's';
// adding the 'fadeOut' class to the supplied node:
el.classList.add('fadeOut');
// setting the transition property of the node,
// 'all' : we're transitioning all (animatable) CSS properties,
// 'delayInSeconds' : the transition-duration,
// 'linear' : the transition timing function,
// 'delayInSeconds' : the transition-delay;
// this animates between the properties defined in the CSS
// for the '.error_message' class and those defined in the
// (more specific) '.error_message.fadeOut' rules:
el.style.transition = 'all ' + delayInSeconds + ' linear ' + delayInSeconds;
}
// Using Function.prototype.call() along with Array.prototype.slice to
// convert the results of document.querySelectorAll() into an Array rather
// than a NodeList; iterating over the Array using Array.prototype.forEach():
Array.prototype.slice.call(document.querySelectorAll('div.error_message'), 0).forEach(function (node) {
// the first argument (here: 'node') is the array-element of the array
// over which we're iterating.
// calling the function, passing the current array-element (a node):
wordDependentFadeOut(node);
});
参考文献: