JQuery animate border without moving div

前端 未结 4 1659
天命终不由人
天命终不由人 2021-01-04 23:12

I want to animate a div by first making it\'s border thicker by 5px on mouseenter, then decreasing the border by 5px on mouseleave, the tricky part is that I don\'t want the

4条回答
  •  独厮守ぢ
    2021-01-04 23:26

    So I finally found my own answer. To reiterate what I wanted:

    1. Circular divs
    2. Animation of increasing border width
    3. Don't want the div to look like it's "moving", only the borders should be the moving parts

    I achieved this by animating BOTH the margin and border at the same time, because if you just animate the border, then the whole div will shift. But if you decrease the margin at the same time as increasing the border, you get the illusion of the div standing still.

    Simply, we have a circular div:

    #somediv {
        display: inline-block;
        height: 200px;
        width: 200px;
        border: solid 0px;
        vertical-align: middle;
        border-radius: 2000px;
        background-color: #ccc;
        margin: 0px;
    }
    

    And with a JQuery function like:

    $(function(){
        $("#somediv").mouseover(function(){
        $(this).animate({"borderLeftWidth" : "5px",
                         "borderRightWidth" : "5px", 
                         "borderTopWidth" : "5px", 
                         "borderBottomWidth" : "5px",
    
                         "marginLeft" : "-5px",
                         "marginTop" : "-5px",
                         "marginRight" : "-5px",
                         "marginBottom" : "-5px"
                        }, 300);
        }).mouseout(function(){
            $(this).animate({"borderLeftWidth" : "0px", 
                             "borderRightWidth" : "0px", 
                             "borderTopWidth" : "0px", 
                             "borderBottomWidth" : "0px",
    
                             "marginLeft" : "0px",
                             "marginTop" : "0px",
                             "marginRight" : "0px",
                             "marginBottom" : "0px"
                            }, 300);
        });
    });
    

    We can achieve what we want.

    Check out this fiffffdle as an example.

    Now, another question up for debate is: We want to be able to only animate the border when the mouse is actually over the circular element inside the div, because if you mouseover the corners of the invisible div box, the circle will animate, but that's not what we want. I will post a link to how we can achieve this later.

提交回复
热议问题