[英]Typescript :Property 'className' does not exist on type 'EventTarget'
I am using draggable in my code like this: First to create and append the element:我在我的代码中使用 draggable 是这样的:首先创建和 append 元素:
let myImg = document.createElement("img");
myImg.setAttribute('src', ...);
myImg.id = some_value;
myImg.className = "store_img";
myImg.draggable = true;
myImg.addEventListener('dragstart',function(event){
event.dataTransfer?.setData("text", somedata);
myImg.style.opacity = "0.5";
myImg.addEventListener('dragend',function(){
mask.style.opacity = "1";
document.getElementById("myStorageDiv")?.appendChild(myImg);
After that, somewhere else I modify the "myStorageDiv" to allow accepting the draggable:之后,我在其他地方修改了“myStorageDiv”以允许接受可拖动:
document.getElementById("myArea")?.addEventListener('dragenter',
function(event){
event.preventDefault();
if(event.dataTransfer?.getData("className") == "store_img"){
this.style.backgroundColor = "red";
}
}, false);
the last line tells me className not exist on 'EventTarget'.最后一行告诉我'EventTarget'上不存在className。 The reason I want to use it is I have two types of draggable, each one only allowed for one area, I want those areas to identify where the draggable comes from before making any changes, ex.'if(event.target.className == "StoreImg"){...}'.
我想使用它的原因是我有两种类型的可拖动,每种只允许一个区域,我希望这些区域在进行任何更改之前识别可拖动的来源,例如'if(event.target.className = =“StoreImg”){...}'。 I also notice dataTransfer's data can only be used in Drop, so I can't pass the className for others like dropenter and dropleave.
我还注意到dataTransfer的数据只能在Drop中使用,所以我不能为dropenter和dropleave等其他人传递className。 Is there any alternative ways for doing it?
有没有其他方法可以做到这一点? Thanks!
谢谢!
Let's see if I understand your issue correctly, you want to change the class for myImg
based on an event and also test which class does it currently have, right?让我们看看我是否正确理解了您的问题,您想根据事件更改 myImg 的
myImg
并测试它当前具有哪个 class,对吗?
TypeScript aside, this should be easily achiavable, here's an example (try dragging the image):除了 TypeScript 之外,这应该很容易实现,这是一个示例(尝试拖动图像):
const myImg = document.querySelector("#my-img"); myImg.addEventListener("dragstart", () => { if (myImg.className == "blue") { alert("Element was blue, I guess."); } myImg.className = "red"; })
.blue { border-style: solid; border-width: 10px; color: blue; }.red { border-style: solid; border-width: 10px; color: red; }
<img id="my-img" class="blue" src="https://www.gravatar.com/avatar/95686594a8e10ec60422e9478e9d1785"></img>
Does that work for you or do you get some TypeScript error?这对你有用还是你得到一些 TypeScript 错误? If you do you can post it here and I'll try to help.
如果你这样做,你可以在这里发布,我会尽力提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.