【发布时间】:2019-11-15 14:30:49
【问题描述】:
我需要动态地将颜色值传递给<input>,以便我可以将 CSS 复制到剪贴板。有问题的颜色是当您更改按钮的背景颜色时会自动更改的颜色。它始终是黑色或白色,并且不会单独传递给--placeholdtext。现在它总是被复制为白色。我使用http://jscolor.com/。我认为该变量存在于 jscolor.js 文件中的某处,无法找到并使用。
我现在的代码:
function copyToClipboard(element) {
let currenttextColor = $(".jscolor").val();
let currenttextStyle = $(element).text();
let newtextStyle = currenttextStyle.replace('--placeholdtext', "#"+currenttextColor);
document.getElementById('myField').value = currenttextColor;
var $tempt = $("<input>");
$("body").append($tempt);
$tempt.val(newtextStyle).select();
document.execCommand("copy");
$tempt.remove();
}
function update(jscolor) {
document.getElementById('button_cont').style.color = '#' + jscolor;
}
#button_cont {
color: --placeholdtext;
font-size: 18px;
text-decoration: none;
padding: 10px;
/* border: 1px solid #ffffff; */
border-radius: 5px 5px 5px 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
display: inline-block;
transition: all 0.4s ease 0s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>
<a href="#" id="button_cont" >Call to action</a>
<button class="jscolor{valueElement:'valueInput', styleElement:'button_cont'}" >
Pick a color
</button>
<input id="valueInput" value="ed3330">
<button onclick="copyToClipboard('style')">Copy button</button></div></div>
<input type="text" id="myField" class="jscolor" onchange="update(this.jscolor);" style="display: none;" />
如您所见,我使用document.getElementById('myField').value = currenttextColor; 将带有颜色的值插入代码下方的<input>,但我找不到所需的黑色或白色值变量。
【问题讨论】:
-
不,字体颜色总是变成黑色或白色,但是当我将它复制到剪贴板时它总是白色,我需要能够用正确的颜色复制 css
-
啊,所以您不想要用户实际选择的(背景)颜色,而是根据 BG 颜色自动为您选择的“互补”黑色或白色文本颜色?然后从链接中读取它 -
window.getComputedStyle(document.getElementById('button_cont')).getPropertyValue('color')(这将为您提供颜色的rgb符号 - 但如果您只是需要知道它是黑色还是白色,那应该可以。) -
谢谢。我知道这是错误的,但是当我将您的代码放在这里
document.getElementById('myField').value = window.getComputedStyle(document.getElementById('button_cont')).getPropertyValue('color');我能够复制正确的 rgb 颜色但只有一次,第二次它给了我这个颜色 rgb 255,255,255 虽然它不是正确的然后它总是给# FFFFFF;我不知道如何使用代码我不是一个好的编码器 -
这样工作:
let currenttextColor = $(".jscolor").val(); let currenttextStyle = $(element).text(); let newtextStyle = currenttextStyle.replace('--placeholdtext', currenttextColor); var actualColor = window.getComputedStyle(document.getElementById('button_cont')).getPropertyValue('color'); document.getElementById('myField').value = actualColor;但是现在您需要按两次复制按钮才能获得正确的颜色。
标签: javascript jscolor