Javascript - Changing border-width without moving surrounding elements.

前端 未结 8 1373
萌比男神i
萌比男神i 2021-02-14 09:43

I have the following HTML:

Hover:


8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 10:33

    Change the width and height of the element by twice the amount of the border-width change (live demo):

    $('.Size').hover(
      function() {
        $(this).css('borderWidth', '5px');
        $(this).css('width', parseFloat($(this).css('width')) - 8 + 'px');
        $(this).css('height', parseFloat($(this).css('height')) - 8 + 'px');
      },
      function() {
        $(this).css('borderWidth', '1px');
        $(this).css('width', parseFloat($(this).css('width')) + 8 + 'px');
        $(this).css('height', parseFloat($(this).css('height')) + 8 + 'px');
      });
    

    Note: This will only work if the border-width, width, and height use the same unit of length. If using a unit other than 'px', change that accordingly.

提交回复
热议问题