简体   繁体   English

使用javascript动态创建onmouseover / onmouseout函数吗?

[英]Create onmouseover/onmouseout functions dynamically with javascript?

So here is an example of the function I need to replicate: 因此,这是我需要复制的功能的示例:

document.getElementById('img1').onmouseover = function() {
    document.getElementById('img1').style.width = expandTo + '%';

    expandCompensate(1);
}

document.getElementById('img1').onmouseout = function() {
    expandReset();
}

The situation is that I have a for loop creating some div elements, and the number of them is dynamic. 情况是,我有一个for创建一些div元素的for循环,并且它们的数量是动态的。 As of right now, I have it creating 4 div elements, so I created 4 iterations of the above functions for img1 , img2 , img3 and img4 . 截至目前,我已经创建了4个div元素,因此为img1img2img3img4创建了上述函数的4个迭代。 But what I would like to do is to have the onmouseover and onmouseout functions created dynamically based on how many div elements I've decided to create (based on a variable). 但是我想做的是根据我决定创建的div元素(基于变量)动态创建onmouseoveronmouseout函数。

Is there any way to do this? 有什么办法吗? Here is all the code for context (it's not much), there are comments in the JS with explanations for everything. 这是所有上下文的代码(不多),JS中有注释,并提供了所有解释。 The part I'm trying to automate is at the bottom: 我要自动化的部分在底部:

https://jsfiddle.net/4w0714su/3/ https://jsfiddle.net/4w0714su/3/

And here is the working example for context of what I'm trying to achieve: 这是我要实现的目标的工作示例:

http://www.ericsartor.ca/imgwide http://www.ericsartor.ca/imgwide

FYI: The image is I picked were random, I just needed high res images. 仅供参考:我选择的图像是随机的,我只需要高分辨率图像。 Just doing this for practice! 只是为了练习而已! Thanks to anyone that can help me figure this out! 感谢任何可以帮助我解决这个问题的人!

I can't understand your code very well, but I'll answer particularly what you're asking. 我不太了解您的代码,但是我会特别回答您的要求。

You can achieve what you want by doing a loop: 您可以通过执行循环来实现所需的目标:

for (var i = 0; i < 4; i++) {
  document.getElementById('img' + i).onmouseover = function() {
    this.style.width = expandTo + '%';
    expandCompensate(Number(this.id.replace('img', '')));
  };

  document.getElementById('img' + i).onmouseout = function() {
    expandReset();
  }
}

Note: you can't use the i variable inside the event handlers' functions, because it will always be 4 , since it will finish the loop, and will never be changed again. 注意:您不能在事件处理程序的函数中使用i变量,因为它将始终为4 ,因为它将完成循环,并且永远不会再次更改。


Another way of doing that is by using an IIFE (Immediately-invoked function expression) , eg: 完成此操作的另一种方法是使用IIFE(立即调用的函数表达式) ,例如:

for (var i = 0; i < 4; i++) {
  (function(n) {
    document.getElementById('img' + n).onmouseover = function() {
      this.style.width = expandTo + '%';
      expandCompensate(n);
    };

    document.getElementById('img' + n).onmouseout = function() {
      expandReset();
    }
  })(i);
}

Doing that, you're passing to a function the current i value, so in that scope, the value of n will be a different one for each execution, eg 0 , 1 , 2 and 3 . 这样做,你正在传递给函数的电流i值,所以在该范围,值n将是一个不同的一个为每个执行,例如0123

An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping. 立即调用的函数表达式(或IIFE,发音为“ iffy”)是一种JavaScript设计模式,该模式使用JavaScript的函数作用域生成词法范围。

This could be achieved by iterating all those DOM elements and binding events in a loop . 这可以通过遍历所有这些实现DOM元素和具有约束力的事件loop

As we bind events in loop , and event callback is being executed later when loop would be iterated completely, we need to maintaing the value of current iteration using CLOSURE . 当我们将事件绑定到loop ,并且当将完全迭代loop ,稍后将执行事件callback ,因此需要使用CLOSURE维护当前迭代的值。

Try this snippet: 试试以下代码片段:

 var pageHeight = document.getElementById('findBottom').getBoundingClientRect().bottom, numOfPics = 4; //the number of div elements to create //creates the div elements within a container div in the HTML document for (var i = 1; i <= numOfPics; i++) { document.getElementById('imgContain').innerHTML += '<div id="img' + i + '" class="imgPane"></div>'; } //used to resize all divs if the window changes size window.onresize = function() { pageHeight = document.getElementById('findBottom').getBoundingClientRect().bottom; for (var i = 1; i <= imgClasses.length; i++) { document.getElementById('img' + i).style.height = pageHeight + 'px'; } for (var i = 1; i <= imgClasses.length; i++) { document.getElementById('img' + i).style.width = 100 / imgClasses.length + '%'; } }; //sets the height of each div to be the mximum height of the page (without scrolling) for (var i = 1; i <= numOfPics; i++) { document.getElementById('img' + i).style.height = pageHeight + 'px'; } //makes all the divs equal percentage widths for (var i = 1; i <= numOfPics; i++) { document.getElementById('img' + i).style.width = 100 / numOfPics + '%'; } //the percentage of the page the hovered image will expand to var expandTo = 40; //function for when an image is hovered over function expandCompensate(whichImg) { for (var i = 1; i <= numOfPics; i++) { if (i != whichImg) document.getElementById('img' + i).style.width = (100 - expandTo) / (numOfPics - 1) + '%'; } } //function for when the hovered image is left to reset the widths function expandReset() { for (var i = 1; i <= numOfPics; i++) { document.getElementById('img' + i).style.width = 100 / numOfPics + '%'; } } (function bindEvents() { for (var i = 1; i <= numOfPics; i++) { document.getElementById('img' + i).onmouseover = (function(i) { return function() { document.getElementById('img' + i).style.width = expandTo + '%'; expandCompensate(i); } })(i); document.getElementById('img' + i).onmouseout = function() { expandReset(); }; } })(); 
 body, p, div { margin: 0; padding: 0; } body {} #findBottom { position: absolute; bottom: 0; } .imgPane { float: left; background-position: center; transition: width 0.25s; } #img1 { background-image: url('http://www.ericsartor.ca/imgwide/img//1.jpg'); } #img2 { background-image: url('http://www.ericsartor.ca/imgwide/img//2.jpg'); } #img3 { background-image: url('http://www.ericsartor.ca/imgwide/img//3.jpg'); } #img4 { background-image: url('http://www.ericsartor.ca/imgwide/img//4.jpg'); } 
 <div id="imgContain"></div> <!-- ABSOLUTE ELEMENTS --> <div id="findBottom"></div> <!-- ABSOLUTE ELEMENTS --> 

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

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