我需要使用保存颜色 id 的按钮记录输出



我有一个代码,可以生成一个可点击的框,该框通过在单击鼠标时循环切换绿色阴影>将颜色从黑色->绿色--白色更改为白色。我需要集成代码,允许当前选择(当前显示的任何阴影(在按下按钮时在输出中可见。假设我单击该框 12 次以更改颜色。然后,我会点击一个按钮,例如"保存",当前显示在框中的任何阴影都会出现在输出中。附上我拥有的代码。我需要帮助实现按钮,该按钮将允许我记录按钮按下情况,以便我可以看到人们正在选择哪些颜色。此外,是否可以将这些输出直接保存到 excel 文件中?这样,他们点击保存按钮,它就会执行将所选阴影直接转换为 excel 文档的代码。

var div = document.querySelector('#myDiv')
div.dataset.color = 0;
div.addEventListener('click', () => {
div.dataset.color = parseInt(div.dataset.color) + 5;
var c = Math.min(div.dataset.color % 512, 255);
var c2 = Math.max((div.dataset.color % 512) - 255, 0);
div.style.background = 'rgb(' + c2 + ',' + c + ',' + c2 + ')';
})
#myDiv {
width: 200px;
height: 200px;
background: #000000;
}
<div id="myDiv"></div>

像这样做:

颜色值将以 RGB 为单位。

使用 JS:

document.getElementById("myDiv").style.backgroundColor -  will extract the background color

使用 jQuery:

jQuery('#myDiv').css("background-color");

var div = document.querySelector('#myDiv')
div.dataset.color = 0;
div.addEventListener('click', () => {
div.dataset.color = parseInt(div.dataset.color) + 5;
var c = Math.min(div.dataset.color % 512, 255);
var c2 = Math.max((div.dataset.color % 512) - 255, 0);
div.style.background = 'rgb(' + c2 + ',' + c + ',' + c2 + ')';
})
function GetCol()
{
alert(document.getElementById("myDiv").style.backgroundColor);
document.getElementById("ColValue").value = document.getElementById("myDiv").style.backgroundColor;
}
#myDiv {
width: 200px;
height: 200px;
background: #000000;
}
<div id="myDiv"></div>
<input type="button" id="btn" value="save and show col" onClick="GetCol()">
<input type="text" id="ColValue">

然后在获取颜色值后,使用一些服务器端语言(如 php(将此值保存到 excel、db 或任何您希望保存此值的内容。

您可以使用 getComputedStyle(( 获取元素的当前样式:

请在此处查找示例

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_getcomputedstyle

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the computed background color for the test div.</p>
<p><button onclick="myFunction()">Try it</button></p>
<div id="test" style="height: 50px;background-color: lightblue;">Test Div</div>
<p>The computed background color for the test div is: <span id="demo"></span></p>
<script>
function myFunction(){
    var elem = document.getElementById("test");
    var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
    document.getElementById("demo").innerHTML = theCSSprop;
}
</script>
</body>
</html>
var getColorOnClick = function(e) {
  e.preventDefault();
  var elem = document.getElementById("mybutton");
  var bgcolor = window.getComputedStyle(elem,null).getPropertyValue("background-color");
  // do something with bgcolor
}

最新更新