gpt4 book ai didi

javascript - 根据数组中的值动态更改 CSS

转载 作者:行者123 更新时间:2023-11-30 15:58:15 24 4
gpt4 key购买 nike

我有这部分 html:

<h1 class="gr-title uppercase">
<span class="title-red">GET MORE</span>
<span id="wordSwap" class="title-black">PROFITS</span>
</h1>

...以及更改 ID 为 wordSwap 的跨度值的 jquery 代码:

(function(){

//Words:
var words = [
'Profits',
'Freedom',
'Time',
'Enjoyment',
'Disconnection',
'Value'
], i = 0;

setInterval(function(){
$('#wordSwap').fadeOut(function(){
$(this).html(words[i=(i+1)%words.length]).fadeIn();
});
// 2 second interval
}, 2000);

})();

我正在尝试根据下一个值/单词更改数组中每个值的 letter-spacing,但我卡住了,无法让它工作。例如,我希望“Time”这个词的字母间距 = 30px,“Value”这个词的 20px,等等。我怎样才能完成这项工作?

这是我到目前为止的一个 jsfiddle:https://jsfiddle.net/vgum6jn6/

//Swap words effect
(function() {

// List of words:
var words = [
'Profits',
'Freedom',
'Time',
'Enjoyment',
'Disconnection',
'Value'
], i = 0;

setInterval(function() {
$('#wordSwap').fadeOut(function() {
$(this).html(words[i = (i + 1) % words.length]).fadeIn();
});
// 2 seconds
}, 2000);

})();
.gr-title {
font-family: "Arial", Georgia, Serif;
}

.uppercase {
text-transform: uppercase;
}

.title-red {
color: #CB0000;
}

.title-black {
color: #191919;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<h1 class="gr-title uppercase">
<span class="title-red">GET MORE</span> <span id="wordSwap" class="title-black">PROFITS</span>
</h1>

最佳答案

尝试这样的事情:

var baseWidth = 100; //some value
setInterval(function(){
$('#wordSwap').fadeOut(function(){
$(this).html(words[i=(i+1)%words.length]).fadeIn()
.css('letter-spacing','') //reset spacing
.css('letter-spacing', function(){
var ratio = baseWidth / $(this).prop('offsetWidth');
return ratio + 'px';
});
});
// 2 second interval
}, 2000);

关于javascript - 根据数组中的值动态更改 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com