如何使用 JavaScript 变量调整 CSS 属性?

问题描述 投票:0回答:2

我的问题:

嘿伙计们。我只是有一个关于使用 JavaScript 更改 CSS 属性的问题。我想使用我在 JavaScript 中编写的方程式来更改 CSS 属性的值。

我的目标是每个元素的亮度根据其与当前所选项目的距离(就其“zIndex”而言)而变化。

我尝试过的:

我尝试过在 CSS 中声明变量,例如过滤器属性的“var(--brightness)”,但我还不太了解它,所以我无法让它工作,而且我也不知道甚至知道在这种情况下这是否是正确的策略。

我希望所选项目的亮度为 100%,并将其旁边的每个元素的亮度增加 30%,直到到达末尾。

有人能帮我找出我做错了什么吗?

我的代码:

HTML:

<body>
    <div class="container">
        <div class="div-items">
            <img class="current-item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
            <img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
            <img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
            <img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
            <img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
        </div>
    </div>
</body>

CSS:

:root {
  --brightness: 1;
}

body {
  height: 100%;
}
  
.container {
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: white;
  width: 100%;
}

.item {
  position: fixed;
  left: -37px;
  top: -37px;
  cursor: pointer;
  filter: var(--brightness);
  transition: filter 0.5s;
}
  
.current-item {
  transition: filter 0.5s;
}

JavaScript:

var items = document.getElementsByClassName('item');

for (i = 0; i < items.length; i++) {
            
var itemClass = items[i].classList
var currentItemIndex = 0;

if (itemClass.contains('current-item')) { // If it is the current item, then this:

    items[i].style.filter = 'brightness(1)'; // Change brightness to 100%
    currentItemIndex = i; // Change current item to this position
                             
    } else if (!itemClass.contains('current-item')) { // If it is not the current item, then this:
        
        var brightness = (100 + (Math.abs(currentItemIndex - i) * 30)) / 100; // Increase by 30% for every position away from current item and assign the float to the variable
        items[i].style.setProperty('--brightness', brightness); // Change the value of "--brightness" to the float assigned to "brightness"
                         
    }
    
}
javascript html css
2个回答
2
投票

不需要 CSS 变量。 您可以直接设置过滤器属性的值:

items[i].filter = "brightness(" + brightness + "%)”;

其中可变亮度是方程的结果。


0
投票

我为您提供了一个使用 JavaScript 设置任何 HTML 元素的任何 CSS 属性的非常基本的示例。假设您有以下 HTML“div”元素,其 id 为“div1”,其中包含一些文本内容,并且您希望根据需要设置该 div 的样式。

<div id="div1">I'm HTML</div>

下面是基本上用于设置此 div 样式的 JavaScript 代码,相同的想法可以应用于 HTML 中的任何位置。

const myDiv = document.getElementById("div1");
myDiv.style.color = "yellow";

您仍然可以选择设置颜色以外的任何其他 CSS 属性的样式,并且您可以使用 JavaScript 来设置 CSS 样式。

© www.soinside.com 2019 - 2024. All rights reserved.