我有html的这一部分:
<h1 class="gr-title uppercase">
<span class="title-red">GET MORE</span>
<span id="wordSwap" class="title-black">PROFITS</span>
</h1>
...这个jquery代码用ID wordSwap改变了span的值:
(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,依此类推。我怎么能这样做?
以下是我现在所做的事情: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>
答案 0 :(得分:1)
尝试这样的事情:
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);
答案 1 :(得分:1)
Alex Kudryashev帮助我提出了这个问题,它完美地解决了我的问题:
//Swap words effect:
var words = [
{ word: 'Profits', spacing: '8px' },
{ word: 'Enjoyment', spacing: '0px' },
{ word: 'Freedom', spacing: '4px' },
{ word: 'Disconnection', spacing: '-2px' },
{ word: 'Time', spacing: '0.98em' },
{ word: 'Value', spacing: '0.5em' }
], i = 0, n = 0;
setInterval(function () {
$('#wordSwap').fadeOut(function () {
$(this).html(words[i = (i + 1) % words.length].word)
.css('letter-spacing', words[n = (n + 1) % words.length].spacing).fadeIn();
});
// 2 seconds
}, 2000);
(忽略随机字母间距值,它们随机用于测试目的)