Onmouseover this src javascript

Обработка событий onmouseover и onmouseout

Процесс обработки любого события — это создание какой-либо функции и добавление ее в качестве обработчика для конкретного элемента. Прочитать о способах обработки событий вы можете в статье «Обработка событий в JavaScript».

Пример обработчика события onmouseover как атрибута элемента

Сейчас речь пойдет о событии onmouseover, которое происходит, когда указатель мыши перемещается на элемент или на один из его дочерних элементов. Например,

Наведи мышь, и текст покраснеет

Однако, это событие редко используется самостоятельно. Обычно оно «идет в паре» с обработкой события onmouseout, которое происходит , когда пользователь убирает указатель мыши с элемента или с одного из его дочерних элементов, т.е. выполняет действие, обратное для onmouseover. Посмотрим, как похожий пример будет выглядеть с обработкой 2-х событий:

Наведи мышь, и текст покраснеет, а потом почернеет снова

В примерах выше в обоих случаях было использовано ключевое слово this , которое указывает на объект, к которому применяется обработчик события. В нашем случае это был абзац с текстом.

Если задуматься о сути того, что было сделано, то мы просто сымитировали двумя обработчиками событий работу псевдокласса :hover :

Наведи мышь, и текст покраснеет, а потом почернеет снова

Данный пример говорит о том, что если обработку каких-то событий в JS можно заменить с помощью CSS-свойств, лучше отдать предпочтение стилям.

Обработка наведения/уведения курсора мыши для изображений

Рассмотрим пример посложнее. Предположим, на нужно заменить одно изображение другим. Просто так это в CSS или HTML не сделать, хотя можно использовать свойства background-image или свойство content:url() в псевдоэлементах ::before или ::after. Для тега это нужно будет сделать с помощью JavaScript:

Boat

Наведите курсор мыши на изображение, а затем уберите его

Смена изображений с анимацией

В том случае, если вам необходимо сменять изображения с анимационным эффектом, например, плавного появления изображения из opacity , можно использовать css-свойство animation . Чтобы анимация запускалась не при появлении изображения, а в момент смены src , управлять этим процессом будем с помощью класса active. И при наведении, и при уведении курсора мыши мы будем сначала добавлять класс active с помощью свойства classList и его метода .add() , а затем удалять этот класс через 500ms, которые соответствуют 0.5s, определенных в свойстве animation для класса active . Удалять класс бцдем методом remove() того же свойства classList , но задавать это будем с помощью метода setTimeout и стрелочной функции.

Пример с анимационным переходом при обработке событий onmouseover и onmouseout:

Headphones

Наведите курсор мыши на изображение, а затем уберите его

Пример обработки событий onmouseover и onmouseout с делегированием событий

В примере выше при наведении/уведении курсора мыши изображение меняется на другое и затем опять происходит возврат к отображению первой картинки. Мы усложним задачу и сделаем несложный вариант увеличения картинки в отдельном блоке при наведении курсора мыши на нее. Что-то подобное, но в более сложном варианте, предлагают обычно интернет-магазины одежды.

Для примера нам понадобится 2 div-а-контейнера:

  1. для 4х небольших изображений, уменьшенных с помощью css-кода
  2. для увеличенного изображения с абсолютным позиционированием

Ниже представлена разметка и CSS-стили.

Обратите внимание, что здесь использована обработка событий с помощью метода addEventListener . В этом случае вместо onmouseover ( onmouseout ) записывается только название, а не обработчик события — mouseover ( mouseout ).

Делегирование событий заключается в том, что мы не писали обработчики для каждого тега img , а задали всего один для их родительского элемента — div-a c . В функции же, которая обрабатывает действия пользователя, мы использовали строку var target = event.target для того, чтобы определить целевой объект события, т.е. тег img .

Также в коде мы учли, что между изображениями в div-e есть отступы, которые относятся к родительскому элементу, поэтому строка if (target.tagName != «IMG») проверяет, а является ли наш целевой объект тегом , и только в этом случае отображает увеличенное изображение. Вы можете самостоятельно отследить, для какого элемента наступает событие при наведении курсора мыши с помощью строки console.log(target.tagName) и консоли в браузере (ее вызывает клавиша F12), если откроете пример в новой вкладке.

На скриншоте представлена консоль в браузере Mozilla Firefox. Стрелками показаны места наведения указателя мыши.

div-img

Вам может понравиться

set-in-js

Использование коллекции Set в JavaScript

try-catch-finally-throw

Использование throw и конструкции try . catch . finally в Javascript

prompt-confirm-js

Диалоговые окна prompt() и confirm()

8 комментариев

Можно скопировать, на самом деле.
Для этого есть кнопка в виде 2-х листочков. Нажимаете на нее и CTRL + C, а потом CTRL + V в свой файл.

Это, похоже, ответ на предыдущий комментарий насчет плавной смены изображений при наведении.
Лучше использовать для этой цели свойство animation из примера.

Источник

Change image onmouseover

Ok, this is working, but how to change back to the original image after mouseout ? If it is possible, I want to do this thing inline, without document.ready function.

8 Answers 8

here’s a native javascript inline code to change image onmouseover & onmouseout:

$('#imageid').hover(function() < $(this).attr('src', '/folder/image2.jpg'); >, function() < $(this).attr('src', '/folder/image1.jpg'); >); 

DEMO

EDIT: (After OP HTML posted)

$('#name img').hover(function() < $(this).attr('src', '/ico/view1.png'); >, function() < $(this).attr('src', '/ico/view.png'); >); 

DEMO

Thy to put a dot or two before the /

  
$(document).ready(function() < $( "#myImg" ).mouseover(function()< $(this).attr("src", "http://www.jqueryui.com/images/logo.gif"); >); $( "#myImg" ).mouseout(function()< $(this).attr("src", "http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"); >); >); 

Edit: Sorry, your code was a bit strange. Now I understood what you were doing. 😉 The hover method is better, of course.

jQuery has .mouseover() and .html() . You can tie the mouseover event to a function:

  1. Hides the current image.
  2. Replaces the current html image with the one you want to toggle.
  3. Shows the div that you hid.

The same thing can be done when you get the mouseover event indicating that the cursor is no longer hanging over the div.

You can do that just using CSS.

a#name span < background-image:url(image/path); >a#name:hover span < background-image:url(another/image/path); >
   

I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img , without «wrapping» it into the a tag (so instead of the document.MyImage , I used this.src )

 hover effect

It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

Источник

Javascript — Change src at onmouseover and onmouseout

I want to do that onmouseover change the image and onmouseout it returns the default image. I use this code:

 
&t=','Condividi su Facebook','height=300, width=750,scrollbars=no, resizable=yes')"> Condividi su Facebook
/#disqus_thread"> Commenta l'articolo

Now, it works the onclick functions but the images remains the same, so the onmouseover and onmouseout doesn’t work. Thanks

Источник

onmouseover function Javascript

I am having a problem with changing onmouseover and onmouseout attributes on dynamic pictures. The way i want it to work is whenever i put my mouse over images the images must change and when i take my mouse away it must be changed to the original picture. and whenever i select any image, that image must be changed to the image which was displayed while moving the mouse across the image. and when i select any other image the same process must take place but the previous image that was changed must be changed back to the original picture. I have accomplished all of the above but my problem is when i select multiple pictures and put my mouse over images that were previously selected, those images do not change (onmouseover attribute does not work on them anymore).

  




Is this a learning exercise, or for an actual website? If the latter, I would recommend you give jQuery a shot. That 16 or so lines of script would likely reduce to about 2 or 3.

1 Answer 1

I’d say you don’t need the lines that are resetting the onmouseover events.

There’s no need to rewrite the onmouseover events — all you want to change is the img src attribute.

As Adam mentions, there’s more modern ways to do this using jQuery — look at:

If i don’t reset the onmouseover events then the image that is selected will do the exact same thing like other images.

Источник

Javascript onmouseover and onmouseout when creating programmatically

I’ve found explanations on Stack Exchange on how to do this for an already existing image tag, like this:

 

but if I’m programmatically creating it as below, I can’t figure out how to use single and double quotations properly to get the code to compile and function.

$('')appendTo('#action' + i); 

Consider using jQuery to add your event handlers rather than putting it in your HTML. See the on method at jQuery.com.

2 Answers 2

You would need to use escaped single quotes around the JS strings in the attributes (i.e. \’ ). You are also missing the . before appendTo .

$('').appendTo('#action' + i); 

However, a more-readable way to do this would be to use jQuery’s attr method.

$('') .attr('onmouseover', 'this.src="https://stackoverflow.com/questions/27586615/hover.jpg";') .attr('onmouseout', 'this.src="https://stackoverflow.com/questions/27586615/original.jpg";') .appendTo('#action' + i); 

You can even get really dynamic, and use event delegation and data attributes, to completely separate content and functionality, and get rid of the ugly event attributes.

//Create an example image. var i = 1;//for example $('') .attr('src', 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png') .attr('data-hoverover', 'https://cdn.sstatic.net/stackexchange/img/logos/se/se-icon.png') .attr('data-hoverout', 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png') .appendTo('#action' + i); //Handle swapping. $(document) .on('mouseenter', 'img.swap', function() < var $this = $(this); $this.attr('src', $this.attr('data-hoverover')); >) .on('mouseleave', 'img.swap', function() < var $this = $(this); $this.attr('src', $this.attr('data-hoverout')); >);

Источник

Читайте также:  Как сдвинуть влево код html
Оцените статью