如何将悬停jQuery转换为纯JS?

时间:2020-07-11 14:47:17

标签: javascript jquery

我在js上有以下代码:

$(".custom-option:first-of-type").hover(function() {
  $(this).parents(".custom-options").addClass("option-hover");
}, function() {
  $(this).parents(".custom-options").removeClass("option-hover");
});

但是我没有找到任何将悬停功能转换为javascript

我有这个:

const firstOption = document.querySelector(".custom-option:first-of-type");
const customSelectTrigger = document.querySelector(".custom-select-trigger");
const customOption = document.querySelector(".custom-option")

customOption.addEventListener("click", function (e) {
  manageOptions(e);
});
customSelectTrigger.addEventListener("click", function (e) {
  showOptions(e);
});
function showOptions(e) {
  e.preventDefault();
  e.stopPropagation();
  selectWrap.classList.add("active");
}
function manageOptions(e){
  e.preventDefault();
  e.stopPropagation();
}

我的html:

        <div class="custom-select-wrapper">
          <select
            name="sources"
            id="sources"
            class="custom-select sources"
            placeholder="Source Type"
          >
            <option value="profile">Profile</option>
            <option value="word">Word</option>
            <option value="hashtag">Hashtag</option>
          </select>
          <div class="custom-select sources">
            <span class="custom-select-trigger">
              Source Type
            </span>
            <div class="custom-options">
              <span class="custom-option undefined">
                profile
              </span>
              <span class="custom-option undefined">
                word
              </span>
            </div>
          </div>
        </div>

当悬停事件发生时,我需要添加一个类,但是我想为纯js做

2 个答案:

答案 0 :(得分:2)

hover()文档开始,该方法基本上是以下方法的简写:

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

所以知道您只需要为事件mouseentermouseleave创建事件监听器

您可以这样做:

['mouseenter','mouseleave'].forEach(eName => {
    firstOption.addEventListener(eName, e => customOption.classList.toggle('option-hover') );
})

答案 1 :(得分:1)

您可以使用import javax.ws.rs.*; import javax.ws.rs.core.Response; @Path("/services") public class Services { @GET @Path("/getpeers") @Produces("application/xml") public Response getPeers() { return Response.ok(ListOfPeers.getInstance()).build(); } @POST @Path("/addpeer") @Consumes("application/xml") public Response addPeer(Peer peer) { int response = ListOfPeers.getInstance().addPeerToList(peer); if(response < 0){ return Response.status(400, "Invalid ID: "+ peer.getId() + " is already in use.").build(); } else return Response.status(200, String.valueOf(response)).build(); } mouseenter并使用mouseleave向该元素添加类:

classList