gpt4 book ai didi

Javascript 代码 getElementByID 与 C# 循环

转载 作者:行者123 更新时间:2023-12-02 23:11:03 24 4
gpt4 key购买 nike

我尝试在代码中使用可拖动的 HTML/JS,但是当我尝试循环每个元素时遇到问题。我无法克服将代码从单个元素转换为 foreach 循环的问题。

这是我的代码:

# CSS CODE
<style>
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}

#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
</style>

# HTML CODE
<div id="mydiv">
<div id="mydivheader">
Firstname Lastname
</div>
</div>

# JAVASCRIPT CODE
<script>
//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}

function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}

function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}

function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>

它适用于一个元素,如上面的示例。但我想像这样循环:

# HTML CODE
@foreach (var player in Model.PlayersToMatchs)
{
<div id="mydiv@(player.Player.PlayerID)">
<div id=" mydivheader@(player.Player.PlayerID)">
@player.Player.Firstname @player.Player.Lastname
</div>
</div>
}

我尝试通过更改第一行来修改我的 Javascript 部分,以考虑部分 id:

dragElement(document.querySelector('[id^="mydiv"]').id);

但是我如何重写这部分:

function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}

谢谢!

最佳答案

正如 Heretic Monkey 所说,querySelector 只返回第一个元素,您需要使用 querySelectorAll 获取所有元素,然后循环 elements 数组来调用 dragElement 函数。

var elements = document.querySelectorAll('[id^="mydiv"]');
elements.forEach(element=> {
dragElement(element);
}
);

关于Javascript 代码 getElementByID 与 C# 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57360316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com