如何使用变量使用JavaScript更改CSS样式的类型



我创建了此vanilla javascript函数,以在我的网站的着陆页上产生视差效果,这很有效,但可能会好得多。

function parallaxTop(direction, id, startingNumber, scrollVariable){
    var scrolled = window.pageYOffset;
    var element = document.getElementById(id);
    element.style.top = (startingNumber + (scrolled * scrollVariable)) + 'px';
}
function parallaxLeft(direction, id, startingNumber, scrollVariable){
    var scrolled = window.pageYOffset;
    var element = document.getElementById(id);
    element.style.left = (startingNumber + (scrolled * scrollVariable)) + 'px';
}
window.onscroll = function() {
    parallaxTop('element1', 0, 0.5);
    parallaxLeft('element2', 200, -0.25);
}

我想知道是否有任何方法可以使用变量选择哪种类型的CSS属性正在更改。这将是我最好的猜测,但我找不到解决方案。

function parallax(direction, id, startingNumber, scrollVariable){
    var scrolled = window.pageYOffset;
    var element = document.getElementById(id);
    element.style.direction = (startingNumber + (scrolled * scrollVariable)) + 'px';
}
window.onscroll = function() {
    parallax('top','element1', 0, 0.5);
}

您应该更改此

element.style.direction = (startingNumber + (scrolled * scrollVariable)) + 'px';

to

element.style[direction] = (startingNumber + (scrolled * scrollVariable)) + 'px';

相关内容

  • 没有找到相关文章

最新更新