我有通過逐步列印文本來列印文本的功能。以及單擊按鈕時發生的事件(即觸發功能時)。但是,如果您多次按下按鈕,文本將列印在另一個按鈕之上。如果有人有任何想法如何處理這個,我真的尋求幫助。并且,如果可能,請提供有關代碼的建議。
function printText(element) {
element.text('')
const text = element.attr('data-text')
let counter = 0
let newText = ''
const print = setInterval(() => {
if(counter <= text.length && text[counter] != undefined){
newText = newText text[counter]
counter
}else{clearInterval(print)}
element.text(newText)
}, 30)
}
accordingButtons.click(function(e){
const $target = $(this)
const $targetBody = $target.attr('class') === 'polygon-but' ? $target.parent().parent().next() : $target.parent().next()
if($target.attr('data-toggle') == 'true'){
$targetBody.animate({
opacity: 0.0,
height: `0px`,
marginTop : '0px'
}, 200)
$target.attr('data-toggle', 'false')
}
else if($target.attr('data-toggle') == 'false'){
$targetBody.animate({
opacity: 1,
height: ` =${$targetBody.attr('data-number')}`,
marginTop : '37px'
}, 200)
$target.attr('data-toggle', 'true')
printText($targetBody)
}
})
uj5u.com熱心網友回復:
將intervalID移到函式外,在setInterval前加一個clearInterval
let print;
function printText(element) {
element.text('')
const text = element.attr('data-text')
let counter = 0
let newText = ''
clearInterval(print)
print = setInterval(() => {
if (counter <= text.length && text[counter] != undefined) {
newText = newText text[counter]
counter
} else {
clearInterval(print)
}
element.text(newText)
}, 100)
}
printText($("[data-text"));
// simulate a second click
setTimeout(() => printText($("[data-text")),1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-text="Never gonna give you up"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535824.html
標籤:javascript查询
上一篇:無法以角度顯示和隱藏按鈕
下一篇:打字稿無法正確確定回呼函式的型別
