我想创建“交互式背景”。当我移动鼠标时,背景会发生变化。
我尝试使用 object.style.background = "rgb(".hex_a.",".hex_b.",".hex_c.")";
显然,这是行不通的。
const paragrapf = document.getElementById("content");
const namebox = document.getElementById("namebox");
const colorbox = document.getElementById("colorbox");
const hashbox = document.getElementById("hashbox");
document.onmousemove = function(e){
var hex_a = e.clientX;
var hex_b = e.clientY;
var hex_c = e.clientX;
colorbox.style.background = "rgb("hex_a", "hex_b", "hex_c")";
}
在colorbox.style.background = "rgb("hex_a", "hex_b", "hex_c")";
我尝试在值之间添加点。我尝试添加不带“引号”的值。 我什至在用于 nub 0-255 的地方直接添加了值。
最佳答案
如果你支持字符串插值:
colorbox.style.background = `rgb(${hex_a}, ${hex_b}, ${hex_c})`;
否则:
colorbox.style.background = 'rgb(' + hex_a + ', ' + hex_b + ', ' + hex_c + ')';
此外,请记住 clientX
和 clientY
可能(在您的情况下肯定会)返回高于 255 的值,这会导致您在使用它们时出现问题在 rgb
函数中。
您必须对范围进行某种映射。您可以在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX
关于javascript - 我正在寻找 style.background 的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414091/