Javascript - Changing border-width without moving surrounding elements.

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

I have the following HTML:

Hover:


相关标签:
8条回答
  • 2021-02-14 10:31

    You can reduce the margin with the same amount that you widen the border.

    If you specify a CSS class for the hover style, then you can just add and remove the class instead of adding inline style to the element. That way all the CSS is in the style sheet instead of scattered in the code, which makes it easier to maintain.

    I rewrote the code to use a style sheet instead of all those inline styles:

    CSS:

    .Size { margin: 10px; border: 1px solid #90A4AF; text-align: center; position: relative; }
    .Size.Small { float: left; height: 600px; width:160px; }
    .Size.Medium { float: left; height: 280px; width: 336px; }
    .Size.Large { height: 90px; width: 728px; }
    .Size > div { position: absolute; top: 50%; text-align: center; }
    .Size.Hover { margin: 6px; border-width: 5px; }
    

    HTML:

    <div style="float:left;">
      <h2>Hover:</h2>
      <br />
      <div class="Size Small" id="160x600">
        <div> Text</div>
      </div>
    
      <div class="Size Medium" id="336x280">
        <div>Text</div>
      </div>
    
      <div class="clear">&nbsp;</div>
    
      <div class="Size Large" id="728x90">
        <div>Text</div>
      </div>
    
    </div>
    

    Javascript:

    $('.Size').hover(
      function() {
        $(this).addClass('Hover');
      },
      function() {
        $(this).removeClass('Hover');
      }
    );
    

    Note: An id should not start with a digit, like for example 160x600.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题