This is an explanation of the video content.
 用技术延续对ACG的热爱
69

 |   | 

A元素相对于B元素调整位置和大小

A将调整为B元素的数值如下:

  • top: bTop+20
  • left: bLeft+20
  • width: bWdith*0.96
  • height: bHeight*0.96

javascript

function alignElementToElement(elementASelector, elementBSelector) {
  // Get the DOM elements for elementA and elementB
  const elementA = document.querySelector(elementASelector);
  const elementB = document.querySelector(elementBSelector);

  // Check if both elements were found
  if (!elementA || !elementB) {
    console.error('One or both elements not found in the DOM:', elementASelector, elementBSelector);
    return;
  }

  // Get the bounding rectangle information of elementB
  const bRect = elementB.getBoundingClientRect();

  // Set the position and size of elementA
  elementA.style.position = 'fixed';
  elementA.style.left = `${bRect.left + 20}px`;
  elementA.style.top = `${bRect.top + 20}px`;
  elementA.style.width = `${bRect.width * 0.96}px`;
  elementA.style.height = `${bRect.height * 0.96}px`;

  console.log(elementA.style.top);
}

// Call the function initially
alignElementToElement('.layui-layer-iframe', '.layui-layer-shade');

// Add an event listener to the window to re-align the elements on resize
window.addEventListener('resize', () => {
  alignElementToElement('.layui-layer-iframe', '.layui-layer-shade');
});

jquery

function alignElementToElement(elementASelector, elementBSelector) {
  // Get the jQuery elements for elementA and elementB
  const $elementA = $(elementASelector);
  const $elementB = $(elementBSelector);

  // Check if both elements were found
  if ($elementA.length === 0 || $elementB.length === 0) {
    console.error('One or both elements not found in the DOM:', elementASelector, elementBSelector);
    return;
  }

  // Get the bounding rectangle information of elementB
  const bRect = $elementB[0].getBoundingClientRect();

  // Set the position and size of elementA
  $elementA.css({
    position: 'fixed',
    left: `${bRect.left + 20}px`,
    top: `${bRect.top + 20}px`,
    width: `${bRect.width * 0.96}px`,
    height: `${bRect.height * 0.96}px`
  });

  console.log($elementA.css('top'));
}

// Call the function initially
alignElementToElement('.layui-layer-iframe', '.layui-layer-shade');

// Add an event listener to the window to re-align the elements on resize
$(window).on('resize', () => {
  alignElementToElement('.layui-layer-iframe', '.layui-layer-shade');
});

69 🖺前端 ↦ JavaScript开发技巧 __ 258 字
 JavaScript开发技巧 #3