简体   繁体   中英

How can I select/mark an item in a list with JavaScript?

I'm trying to select an item in a DOM draggable list so that I can move it to another field with a button. Is there a mouseDown or similar function to mark the selected item?

var nmbrCustomers = 10; // Enter the number of customers!
var customerArray = new Array(nmbrCustomers);

for (var i = 1;i < nmbrCustomers + 1; i++){
  customerArray[i] = "f_" + i
}

customerArray.forEach(myFunc);

function myFunc(item,index){
  console.log(document.getElementById(item).innterHTML);
}

With this code I can reach all the elements I want, but I don't know how to make them selected/marked. The results from the above code gives the following code for each element:

<td class="menuGroup" nowrap="nowrap">
  <img id="someimageID" class="navigatorGroupImage" align="left" 
    src="someimageDir" onclick="toggleGroup(9)" 
    ondragstart="dragStartGroupIcon(event)" alt="Alternar expandir/colapsar">

  <span id="someID" 
    class="navigatorGroupText" draggable="true" 
    onmousedown="mouseDownGroup('f_9', Event.extend(event))" 
    onmouseup="mouseUpGroup('f_9', Event.extend(event))" 
    onmousemove="mouseMoveGroup('f_9', Event.extend(event))" 
    title="someName.">                      
  </span>
</td>

You can dynamically add and remove a CSS class to the dragged element. The following code snippet will work if you add a draggable CSS class to the elements you want to drag - change the CSS rule to suit your requirements.

 let sources = document.querySelectorAll('.draggable'); sources.forEach(source => { source.addEventListener('dragstart', dragStart); source.addEventListener('dragend', dragEnd); }); function dragStart(e) { // Add a 'dragging' CSS class to the element this.classList.add('dragging'); } function dragEnd(e) { // Remove the 'dragging' CSS class this.classList.remove('dragging'); } 
 .dragging { opacity: .50; border: 6px solid #000; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM