проблемы с hover'ом()
Приветствую всех!
Такая беда: <div class="post"> <div class="box"> <a href="#"><img src="img/green.jpg" alt="green.jpg" /></a> <p><a href="#">Lorem ipsum/a></p> </div> <h2><a href="#">Sed ut perspiciatis unde</a></h2> </div> Мне нужно, чтобы при наведении мыши на h2(который в div.post) изображение из div.box обрамлялось, к примеру, красной рамкой(это вообще не суть, предположим, что мне нужно изменить какое-либо из свойств изображения через animate). Я написал для этого код, но поскольку таких дивов с классом post у меня несколько, то при наведении на один заголовок, обрамляются все изображения. Как в таком случае быть? Как определить один конкретный элемент? :-E |
thegreatwhitedope,
Используй метод parents $('h2').hover(function() { var img = $(this).parents('.post').find('img'); img.css({...}); //делаешь что нужно }); |
Метод parents используй только если тебе необходимо найти ближайшего родителя, если же структура иная, то лучше использовать closest().
|
Не буду засорять раздел и задам ещё один вопрос здесь:
<article> <div class="magic-box"> <a href="#"><img src="img/green.jpg" alt="concert.jpg" /></a> <p><a href="#">competition</a></p> </div> <h2><a href="#">Win tickets to Rock en Seine with</a></h2> <h6><a href="#">written by: <span>Mike Shaw</span> published on <span>August 02 2011</span></a></h6> <p><a href="#">Radio stations and TV music channels are all well and good, but they tend to be a little bit insular. They will cover a little bit of new music, but 99% of the time its from British or American artists – meanwhile the rest of the world is out there making...</a></p> </article> <article> <div class="magic-box"> <a href="#"><img src="img/green.jpg" alt="concert.jpg" /></a> <p><a href="#">competition</a></p> </div> <h2><a href="#">Win tickets to Rock en Seine with</a></h2> <h6><a href="#">written by: <span>Mike Shaw</span> published on <span>August 02 2011</span></a></h6> <p><a href="#">Radio stations and TV music channels are all well and good, but they tend to be a little bit insular. They will cover a little bit of new music, but 99% of the time its from British or American artists – meanwhile the rest of the world is out there making...</a></p> </article> <article> <div class="magic-box"> <a href="#"><img src="img/green.jpg" alt="concert.jpg" /></a> <p><a href="#">competition</a></p> </div> <h2><a href="#">Win tickets to Rock en Seine with</a></h2> <h6><a href="#">written by: <span>Mike Shaw</span> published on <span>August 02 2011</span></a></h6> <p><a href="#">Radio stations and TV music channels are all well and good, but they tend to be a little bit insular. They will cover a little bit of new music, but 99% of the time its from British or American artists – meanwhile the rest of the world is out there making...</a></p> </article> Мне нужно, чтобы при наведении на Img подсвечивался h2( а в последующем при наведении на h2 подсвечивался img, при наведении на p подсвечивались и h2 и img). Пишу: $(function(){ var img = $(this).('.magic-box').find('img'); var header = $(this).('article').find('h2 a'); $('.magic-box').hover(function(){ $(this).animate({"background-color":"#000"}, 300), header.animate({"color":"#ddd"}, 300); }, function(){ $(this).animate({"background-color":"#fff"}, 300), header.animate({"color":"#000"}, 300); }) }) Однако ничего не анимируется. Что не так? кривые селекторы? Мои руки? |
$(this).('.magic-box').find('img');- странная запись, так низя вы че, вот $(function(){ var img = $(this).find('.magic-box').find('img'); var header = $(this).find('article').find('h2 a'); $('.magic-box').hover(function(){ $(this).animate({"background-color":"#000"}, 300), header.animate({"color":"#ddd"}, 300); }, function(){ $(this).animate({"background-color":"#fff"}, 300), header.animate({"color":"#000"}, 300); }) }) |
Спасибо! Во внимательности мне не занимать.
Только вот теперь переменные img и header не работают в hover'e. Приходится прописывать их в каждой фунции hover'a (mouseenter/mouseleave). Как сделать их доступными вне hover'a? Ведь они же итак уже глобальные, или нет? |
thegreatwhitedope, а вы уверены, что дело именно header, потому что он должен там определятся, я протестировал этот код у себя, у меня не срабатывал animate, с такими параметрами как у вас, я пробовал вот так, отрабатывает:
$('.magic-box').hover(function(){ $(this).animate({"font-size":"20pt"}, 300); header.animate({"font-size":"1pt"}, 300); }, function(){ $(this).animate({"font-size":"10pt"}, 300), header.animate({"font-size":"10pt"}, 300); }); |
Да, уверен. Возможно, что у Вас не срабатывал animate, потому что для работы animate с цветом должен быть подключен плагин "Color animation".
$(function(){ var header = $(this).parents('article').find('h2 a'); $('.magic-box img').hover(function(){ $(this).animate({"background-color":"#000"}, 300), header.animate({"color":"#ddd"}, 300); }, function(){ $(this).animate({"background-color":"#fff"}, 300), header.animate({"color":"#000"}, 300); }) }) Такой код у меня не срабатывает. Но если инициализировать переменную в каждом ховерском mouseenter/mouseleave, то код работает. Как же, всё-таки, сделать эту переменную доступной для всех? |
thegreatwhitedope, а header у вас точно ни где не переопределяется?ну попробуйте сделать
var header = 1;и вызвать alert(header ) в hover если покажет там 1, значит все должно работать и кстате как у $(this).parents('article') могут быть родитель article?вы же его в тело документа вписываете, проверте сначала лучше alert(header.length) есть ли такой объект вообще |
Я почему-то подумал, что parents() позвращает article как родительский элемент ^^'' Фигню сделал.
исправил вот так: var header = $(this).find('article').find('h2 a'); и теперь все хорошо, header изменяется везде(все заголовки изменяются, хотя изменяться должен только один) и сразу :) Как исправить? :/ Наверное, нужен parents(), только вот где его ипользовать? Не совсем понял, как он работает. |
Часовой пояс GMT +3, время: 05:55. |