嗨所以我有两个Div元素(70px×70px)和两个图像,图像具有HTML5拖放功能,可以拖入Div框。
我想要做的是当图像被拖入div框并点击一个按钮时,我希望div框的边框根据Div内的图像改变颜色。
有没有办法用Javascript做到这一点?图像有ID,所以可以编写一个使用它的函数吗?
这是我的代码:
CSS:
#Drop1 {width:70px;height:70px;padding:10px;border:1px solid#aaaaaa;}
#Drop2 {width:70px;height:70px;padding:10px;border:1px solid#aaaaaa;}
JS:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text/html", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data=ev.dataTransfer.getData("text/html");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "newId";
ev.target.appendChild(nodeCopy);
}
HTML:
<body>
<div id="Drop1" ondrop="drop(event)" ondragover="allowDrop(event)"> </div>
<div id="Drop2" ondrop="drop(event)" ondragover="allowDrop(event)"> </div>
<img id="drag1" src="forward.png" draggable="true" ondragstart="drag(event)" width="64" height="64">
<img id="drag2" src="left.png" draggable="true" ondragstart="drag(event)" width="64" height="64">
</body>
答案 0 :(得分:1)
这是你想要完成的事吗?
JS
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text/html", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text/html"),
nodeCopy = document.getElementById(data).cloneNode(true),
type = nodeCopy.src;
nodeCopy.id = "newId";
ev.target.appendChild(nodeCopy);
if(type.indexOf(".png") !== -1) {
ev.target.className = 'red-border';
} else if(type.indexOf(".jpg") !== -1) {
ev.target.className = 'green-border';
} else {
ev.target.className = 'gray-border';
}
}
CSS
#Drop1 {width:70px;height:70px;padding:10px;border:1px solid#aaaaaa;}
#Drop2 {width:70px;height:70px;padding:10px;border:1px solid#aaaaaa;}
#Drop1.red-border,
#Drop2.red-border {
border: 1px solid red;
}
#Drop1.green-border,
#Drop2.green-border {
border: 1px solid green;
}
#Drop1.gray-border,
#Drop2.gray-border {
border: 1px solid darkgray;
}
使用按钮
更新了版本function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text/html", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text/html"),
nodeCopy = document.getElementById(data).cloneNode(true),
type = nodeCopy.src;
nodeCopy.id = "newId";
ev.target.appendChild(nodeCopy);
}
function checkImages() {
var drop1Elem = document.getElementById('Drop1'),
drop2Elem = document.getElementById('Drop2');
if(drop1Elem.childNodes.length >= 1) {
if(drop1Elem.childNodes[0].className === 'item1') {
drop1Elem.className = 'red-border';
} else if(drop1Elem.childNodes[0].className === 'item2') {
drop1Elem.className = 'green-border';
} else {
drop1Elem.className = 'gray-border';
}
}
if(drop2Elem.childNodes.length >= 1) {
if(drop2Elem.childNodes[0].className === 'item1') {
drop2Elem.className = 'red-border';
} else if(drop2Elem.childNodes[0].className === 'item2') {
drop2Elem.className = 'green-border';
} else {
drop2Elem.className = 'gray-border';
}
}
}