【发布时间】:2018-07-09 04:14:00
【问题描述】:
我正在尝试使用 jQuery 淡出一个元素,替换其 innerHTML 并在替换内容后将其淡入。使用.html()-方法和.find()-方法替换元素的内容是可行的,但是一旦我尝试向查找和放置innerHTML的函数添加延迟,它就会停止工作.到目前为止,这是我的代码:
'#current-title' 是应该替换其内容的元素; '#title1' 包含应该以 '#current-title' 结尾的文本。在放置新文本之前和之后,所有这些都应该通过 '#current-title' 的过渡不透明度更改来实现。
$(document).ready(function() {
$.replace = function() {
$('#current-title').css("opacity", "0");
setTimeout(function() {
$('#current-title').html($(this).find('#title1').html());
}, 500);
setTimeout(function() {
$('#current-title').css("opacity", "1");
}, 1000);
alert('Title has been replaced.');
};
$(".replace-btn").click(function() {
$.replace();
});
});
相同功能的简化版本,仅替换'#current-title' 的html 而没有setTimeout,效果很好:
$(document).ready(function() {
$.replace = function() {
$('#current-title').html($(this).find('#title1').html());
alert('Title has been replaced.');
};
$(".replace-btn").click(function() {
$.replace();
});
});
为什么我的第一段代码中的setTimeout 不起作用?
$(document).ready(function() {
$.replaceDelayed = function() {
$('#current-title').css("opacity", "0");
setTimeout(function() {
$('#current-title').html($(this).find('#title1').html());
}, 500);
setTimeout(function() {
$('#current-title').css("opacity", "1");
}, 1000);
setTimeout(function() {
alert('Title has been replaced.');
}, 1000);
};
$(".replace-btn").click(function() {
$.replaceDelayed();
});
});
$(document).ready(function() {
$.replaceNormal = function() {
$('#current-title').html($(this).find('#title1').html());
alert('Title has been replaced.');
};
$(".replace-btn2").click(function() {
$.replaceNormal();
});
});
.title {
visibility: hidden;
}
* {
transition: opacity 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-title">
<a>Project Title #0</a>
</div>
<br>
<div class="title" id="title1">
<a>Project Title #1</a>
</div>
<br>
<button class="replace-btn">
Replace Title (with delay)
</button>
<button class="replace-btn2">
Replace Title (without delay)
</button>
【问题讨论】:
-
可以有html代码吗?
-
@ChandraShekhar 当然,等一下,我会设置一个 jsfiddle 并将其添加到问题中
-
@JoSch Stackoverflow 有一个内置的小提琴供您使用。人们会更好、更容易地回答您的问题。
-
那里肯定发生了一些奇怪的事情。将代码嵌入为 stacksn-p 会挂起页面。如果您有兴趣,请查看修订历史:stackoverflow.com/revisions/48518673/4
-
@JoSch 您不需要自己处理不透明度或超时,我的回答基本上只使用 3 行 jQuery 代码:fadeOut、html、fadeIn、工作完成。也不需要 JSFiddle,运行代码 sn-p 看看它是否工作。
标签: javascript jquery html css innerhtml