javascript - 要获得警报消息,如果颜色对话框在没有更改颜色选择的情况下关闭(警告:colorDialog.style.display = "none";)
问题描述
这是用于测试的 js fiddle 上的代码https://jsfiddle.net/em7yfa12/
代码也在这里:但首先让我解释一下代码的作用。然后我会告诉我需要实现什么。我自己找不到路。这就是为什么我在这里寻求解决方案的原因。
当按下“打开输入元素以插入文本”按钮时,提示元素出现获取文本,稍后将其绘制为在颜色对话框中选择的颜色。但是这个事件只有在颜色改变时才会发生,因为这个事件是由颜色对话框的改变触发的。
这都是正常的。但我需要一些额外的东西,那就是:
如果打开了颜色对话框并且在关闭对话框之前没有执行颜色更改,那么我需要得到:
alert("您必须选择与之前案例中选择的颜色不同的颜色才能绘制文本");
<input type="button" id="newlabelID" value="Open input element to insert text "/></br>
<input type="color" id="colorDialogID" ></br>
<a id="aID"> Text to paint</br>
var someText;
function createStatusF(){
someText = prompt("Enter some text :", "");
if ((someText=="")||(someText==null)){
return;
}
document.getElementById("colorDialogID").focus();
document.getElementById("colorDialogID").value = "#FFCC00";
document.getElementById("colorDialogID").click();
}
document.getElementById("newlabelID").onclick = createStatusF;
document.getElementById("colorDialogID").style.display = "none";
function peintTheText(){
document.getElementById("aID").innerHTML= someText;
var theColor=document.getElementById("colorDialogID").value;
document.getElementById("aID").style.color=theColor;
}
document.getElementById("colorDialogID").onchange = peintTheText;
解决方案
您需要使用输入事件并将其附加到颜色输入。这可行,但alert
与颜色选择器一起使用并不是一个好主意,因为颜色选择器的 z 索引将高于警报,因此用户将无法单击它。
这是JS代码:
let someText;
let previousColors = [];
let colorDialog = document.getElementById("colorDialogID");
function openColorPicker() {
colorDialog.focus();
colorDialog.value = "#FFCC00";
colorDialog.click();
}
function createStatusF() {
someText = prompt("Enter some text :", "");
if ((someText == "") || (someText == null)) {
return;
}
openColorPicker();
}
document.getElementById("newlabelID").onclick = createStatusF;
document.getElementById("colorDialogID").style.display = "none";
function peintTheText() {
var theColor = colorDialog.value;
previousColors.push(theColor);
document.getElementById("aID").innerHTML = someText;
document.getElementById("aID").style.color = theColor;
}
function onColorSelected(e) {
const theColor = colorDialog.value;
if (previousColors.includes(theColor)) {
alert("You have to select a different color than any of colors you have selected in previous cases to paint the text");
}
}
colorDialog.addEventListener('input', onColorSelected);
colorDialog.addEventListener('change', peintTheText);
推荐阅读
- html - chrome浏览器中oppo F3 plus的HTML输入maxlength属性问题
- matlab - 将滞后项添加到函数中 [在 MATLAB 中]
- javascript - 如何将对象乘以指定的规则?
- twitter - 如何检测从官方帐户发布的推文?
- node.js - 是否可以在不使用全局文件夹的情况下运行 node.js CL 应用程序?
- angular - 从父级的ajax调用接收数据后如何更新子组件
- express - 为什么 pug 页面不能在 express js 中呈现
- openlayers - Openlayers API 文档
- c# - MIN、MAX 堆叠图表中的指示(在这里停留了一个月..)
- c++ - 如何将 std::vector 设置为模板的默认参数?