简体   繁体   English

javascript在仅悬停一个元素时更改多个元素的文本

[英]javascript changing text of multiple elements while hovering only one element

Having an issue with replacing text in multiple elements while hovering only one element在仅悬停一个元素时替换多个元素中的文本时出现问题

I tried doing document.getElementsbyClassName() but it didnt seem to work我试过做document.getElementsbyClassName()但它似乎没有用

 function replace(text) { var display = document.getElementById('head'); display.innerHTML = ""; display.innerHTML = text; } function revert(text) { var display = document.getElementById('head'); display.innerHTML = ""; display.innerHTML = text; }
 <h2 id="head" onmouseover="replace('oh no!! the heading is gone')" onmouseout="revert('e8')"> e8 </h2> <p id="pp"> :) </p>

I can replace the header but not the paragraph.我可以替换标题但不能替换段落。

Personally I'd recommend a more extensible route revolving around data attributes.我个人建议围绕data属性进行更可扩展的路线。

The benefit to this approach is that you don't need to modify the JavaScript for each new item.这种方法的好处是您不需要为每个新项目修改 JavaScript。 You simply add attributes to the HTML elements themselves.您只需将属性添加到 HTML 元素本身。

See the examples below - comments in the code.请参阅下面的示例 - 代码中的注释。

If each element has it's own hover and replace information:如果每个元素都有自己的悬停和替换信息:

 const elems = document.querySelectorAll('[data-replace]'); elems.forEach(elem => { elem.addEventListener("mouseover", function() { this.dataset["original"] = this.innerHTML; // store the text as data-original this.innerHTML = this.dataset["replace"]; // update the html to be data-replace }); elem.addEventListener("mouseout", function() { this.innerHTML = this.dataset["original"]; // revert back to data-original }); });
 <h2 id="head" data-replace="'oh no!! the heading is gone'">e8</h2> <p id="pp" data-replace="Something else"> :) </p>

If one item being hovered affects others , check out the example below instead.如果悬停的一项影响其他项目,请查看下面的示例。

You can group items by giving them the same data-group attribute.您可以通过为项目提供相同的data-group属性来对项目进行data-group The one with the data-replace attribute is the one that triggers the replacement and defines the text.具有data-replace属性的那个是触发替换并定义文本的那个。

 const elems = document.querySelectorAll('[data-replace]'); elems.forEach(elem => { //Get all elements that have the same data-group as the item being hovered let group = document.querySelectorAll(`[data-group='${elem.dataset.group}']`); elem.addEventListener("mouseover", function() { group.forEach(e => { //For all group elements e.dataset.original = e.innerHTML; //Store the original text e.innerHTML = this.dataset.replace; //Replace the current text }); }); elem.addEventListener("mouseout", function() { group.forEach(e => e.innerHTML = e.dataset.original); //Rever to original text }); });
 <h2 data-group="group1" data-replace="Hello World">heading</h2> <p data-group="group1">p</p> <h2 data-group="group2" data-replace="Goodbye World">heading 2</h2> <p data-group="group2">p 2</p>

Once option would be to pass the mouseover/mouseout event into the function.一次选项是将鼠标悬停/鼠标移出event传递到函数中。 then you could use one function for multiple places.那么你可以在多个地方使用一个函数。

<h2 id="head" onmouseover="replace(this, 'oh no!! the heading is gone', 'pp', 'moused over the heading')" onmouseout="replace(this, 'e8', 'pp', ':)')"> e8 </h2>

<p id="pp"> :) </p>

then use one function that will update the content of whatever element is passed to it.然后使用一个函数来更新传递给它的任何元素的内容。

function replace(e, text, secondElmID, secondElmText) { 
  // update the first element
  e.innerHTML = "";
  e.innerHTML = text;
  // update the second element if is exists
  var secondElm = document.getElementById(secondElmID);
  if (secondElm) {
    secondElm.innerHTML = secondElmText;
  }
}

You just need to make sure that you reference both the elements that need to be affected and change both of them when one of them initiates the event.您只需要确保引用需要影响的两个元素,并在其中一个启动事件时更改它们。

Now, for few notes:现在,请注意以下几点:

 let head2 = document.getElementById("head2"); let display = document.getElementById("pp"); let origHead2 = null; let origPP = null; head2.addEventListener("mouseover", function(){ replace("oh no!! the heading is gone"); }); head2.addEventListener("mouseout", revert); function replace(text) { // Store the original values before changing them origHead2 = head2.textContent; origPP = pp.textContent; // Set the new values to what was passed into the function head2.textContent = text; display.textContent = text; } function revert() { // Set the values back to the originals head2.textContent = origHead2; display.textContent = origPP; }
 <h2 id="head2"> e8 </h2> <p id="pp"> :) </p>

You can proceed by grouping the elements which have the hover and replace text functionality under the same class and give each one a data-txt (where you can change txt part per your requirements) that holds the text that will be shown on hover and also will hold the old text each time an element gets hovered.您可以将具有悬停和替换文本功能的元素分组到同一class下,并为每个元素提供一个data-txt (您可以在其中根据您的要求更改txt部分),其中包含将在悬停时显示的文本以及每次悬停元素时都会保留旧文本。

Here's a demo :这是一个演示:

 /** * txtChange: the elements to be changed (their text) on mouse enter. * doTextChange: a function that handles changing the text back and forth (replace and return to the original) for each element on both mouseenter and mouseleave events. **/ const txtChange = [...document.querySelectorAll('.text-change')], doTextChange = () => { /** loop through the elements **/ txtChange.forEach(el => { /** save the old text **/ const oldTxt = el.textContent; /** replace the old text with the one in the data-txt **/ el.textContent = el.dataset.txt; /** store the old text in the data-txt so that we return to the original text on mouse leave **/ el.dataset.txt = oldTxt; }); }; /** cycle through the elements and attach the events **/ txtChange.forEach(el => { /** the "doTextChange" can handle both the events **/ el.addEventListener('mouseenter', doTextChange); el.addEventListener('mouseleave', doTextChange); });
 /** for demo purposes **/ .text-change { margin: 35px 0; padding: 8px; background-color: #eee; transition: all .4s 0s ease; } .text-change:hover { background-color: #c0c0c0; }
 <!-- the hoverable elements share the same class "text-change" and each one has its own "data-txt" --> <h2 class="text-change" data-txt="new text !">e8</h2> <p class="text-change" data-txt="yet another new text">:)</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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