jQuery - Hover CSS Element 1 change Elevement 2

邮差的信 提交于 2020-01-14 04:27:08

问题


I have two elements:

.navAbout
#slider

On hover of .navAbout, which is an A tag, I need the border color of (div) #slider to change to a specific color. Upon mouseOut, I need #slider to revert back to its original CSS declaration.

I have tried several codes. Here's my most recent:

<script>
      $(".navAbout").hover(function () {
        $("#slider").css({'border-color' : '#3bc624'});
      }, function () {
        var cssObj = {
          'border-color' : '#3bc624',
        }
        $("#slider").css(cssObj);
      });
</script>

Thanks for the help!


回答1:


Something like this should help:

JS

$(".navAbout").hover(function () {
    $("#slider").addClass("coloured-border");
}, function () {
    $("#slider").removeClass("coloured-border");
});

CSS

.coloured-border {
    border-color: orange
}



回答2:


this should do the trick in the direction you are trying

<script type="text/javascript">
$(function(){
      $(".navAbout").hover(function () {
        var slider = $('#slider');
        slider.data('style', slider.attr('style') );
        slider.css({'border-color' : '#3bc624'});
      }, function () {
        var slider = $('#slider');
        slider.attr('style', slider.data('style'));
      });
});
</script>

but the answer of @jakeclarkson is the correct conceptual approach to the problem..




回答3:


Try this

$(".navAbout").hover(
    $("#slider").toggleClass('borderColor');
});

Define a class with required border color

.borderColor
{
    border-color: #FF0000;
}



回答4:


Your approach would work, but you're setting the color to the same thing both times.

Also, I'm not sure if you are only alternating between two colors, or if the color of #slider is set in different places and could be anything. If it could be anything then you'll need to check what it is and save it so that you can set the color back to what it was originally later on.

Ideally you should just change classes like jakeclarkson suggests above and avoid keeping style information in your javascript/css.

See this!

HTML:

<a class="navAbout">Hover over me</a> <div id="slider"> and I'll change</div>

JavaScript:

var originalColor ='';

$(".navAbout").hover(function(event){

   originalColor = $("#slider").css("border-color");
   $("#slider").css("border-color", "#3bc624");

}, function(event){

   $("#slider").css("border-color", originalColor); 

} );

Read:

http://api.jquery.com/hover/

http://api.jquery.com/css/



来源:https://stackoverflow.com/questions/8527145/jquery-hover-css-element-1-change-elevement-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!