| |
A将调整为B元素的数值如下:
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');
});