我有以下Javascript(纯净):
=> ((convert +) square)
25
它的任务是在滚动结束时随机设置CSS属性,然后自动让它们返回初始值。
对我来说有趣的不是结果本身,而是我似乎在这里所做的错误。我认为这只是我个人的拼写/理解JS问题。
因为我已经有一个有效的代码了,
const style = document.documentElement.style;
**var ranges = {
'tx': [-15, 15, 0], // key = css style property, first value = start range random, second value = end range random, third value = initial vlaue to return to
'ty': [-5, 5, 0],
'scale': [0.5, 1.5, 1],
'opacity': [0.5, 0.9, 0]
};**
function valueChange(prop, value, initial) {
style.setProperty('--' + prop, value);
setTimeout ( function() {
style.setProperty('--' + prop, initial);
}, 150)
}
var timer = null;
window.addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
**for (key in ranges) {
valueChange(key, randomBetween(ranges[key][0], ranges[key][1]), ranges[key][2]);
};**
}, 150);
}, false);
function randomBetween(min, max) {
return Math.random() * (max - min) + min;
}
所以我基本上想要实现的是替换粗体显示的代码部分,以使脚本更加专业,减少重复。
假设我愿意与某人分享这个想法,但我想避免使用“愚蠢”的代码(即使工作正常)。
有人可以帮助我吗?
编辑:
所以我不得不使用:
const style = document.documentElement.style;
function valueChange(prop, value, initial) {
style.setProperty('--' + prop, value);
setTimeout ( function() {
style.setProperty('--' + prop, initial);
}, 150)
}
var timer = null;
window.addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
**var newX = randomBetween(-15, 15);
var newY = randomBetween(-5, 5);
var newScale = randomBetween(0.5, 1.5);
var newOpacity = randomBetween(0.5, 0.9);
valueChange('tx', newX + 'vw', 0);
valueChange('ty', newY + 'vw', 0);
valueChange('scale', newScale, 1);
valueChange('opacity', newOpacity, 0);**
}, 150);
}, false);
function randomBetween(min, max) {
return Math.random() * (max - min) + min;
}
和:
var ranges = {
'tx': [-15, 15, 0, 'vw'],
'ty': [-5, 5, 0, 'vw'],
'scale': [0.5, 1.5, 1, ''],
'opacity': [0.5, 0.9, 0, '']
};