简体   繁体   中英

Mootools: How to create new element `span` inside `li` element on mouseove?

The HTML code:

<ul id="el">
   <li></li>
   <li></li>
   <li></li>
   <li></li>
</ul>

How to create new element span inside li element on mouseover?

<ul id="el">
   <li></li>
   <li></li>
   <li><span></span></li><!--on mouseover > new element span-->
   <li></li>
</ul>
document.getElementById('el').addEventListener("mouseover", function(e){
  var e=e.target;
  if (e.nodeName=="LI") {
    var span=e.getElementsByTagName('span')[0];
    if(!span) {
      e.innerHTML="<span></span>";
    }
  }
},false);

This will do a check for an existing SPAN before inserting it. In addition it does not require JQuery or any other JS framework.

Tested on Firefox, but some browsers might handle the e.target part differently so just bear that in mind.

try with this:

document.getElements('#el > li').addEvent('mouseenter', function(e) {
  var target = document.id(e.target);
  if (!target.getElement('span')) target.adopt(new Element('span'));
});

if you want to remove the span on mouse out, then add this:

document.getElements('#el > li').addEvent('mouseleave', function(e) {
  document.id(e.target).getElements('span').destroy();
});

be careful as these are very naive implementations and are the bare minimum you need for it to work.

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