У меня есть несколько хороших рамок с описанием, прикрепленных ко всем кнопкам (см. Рисунок номер 0).
Когда я изменяю размер области просмотра, поле описания просто расширяется за пределы области просмотра. Смотрите на первой картинке 
Очевидно, это связано с тем, что я установил одинаковое положение всех своих абсолютно позиционированных полей описания (вверху: -25 пикселей справа: -79 пикселей), и когда пользователь наводит курсор на кнопку справа, он расширяется слишком далеко. Я мог бы изменить то, что находится справа, но это ничего не решит, так как я не знаю, сколько из этих изображений будет добавлено, когда веб-сайт будет готов.
Поэтому я хочу использовать javascript для изменения положения любого поля описания, которое расширяется за пределы области просмотра, чтобы оно выглядело так, как показано на втором рисунке.
Код, который я использую для этой настройки, находится здесь:
<div id = "grid-container" class = "container">
<div id = "product1" class = "products">
<input id = "one" type = "checkbox" name = "wobblers" value = "one">
<label for = "one">
<img id = "one" src = "https://cdn.shopify.com/s/files/1/1557/0907/products/product-image-507865262.jpg?v=1527268422"
alt = "rapala">
<button id = "product1-info" class = "btn btn-info">info
<div class = "info-box" id = "info-box1"></div>
</button>
</label>
</div>
</div>
CSS:
img {
width: 75px;
}
.info-box {
display: none;
width: 80px;
height: 60px;
background: grey;
position: absolute;
top: -25px;
right: -79px;
border-radius: 10% 10% 10% 1%;
}
#product1-info:hover #info-box1 {
display: block;
}
.products {
display: inline-block;
}
label {
position: relative;
display: inline-block;
vertical-align: middle;
}
#grid-container {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
Спасибо!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


function changeElementPosition() {
const tooltipParent = document.getElementById('product1-info');
const tooltip = document.getElementById('info-box1');
const tooltipParentRightPosition = tooltipParent.getBoundingClientRect().right;
const windowWidth = document.documentElement.clientWidth;
const tooltipInitPosition = -tooltip.getBoundingClientRect().width;
if ((tooltipParentRightPosition - windowWidth) >= tooltipInitPosition) {
tooltip.style.right = tooltipParentRightPosition - windowWidth + 'px';
}
window.addEventListener("resize", () => {
const tooltipParent = document.getElementById('product1-info');
const tooltip = document.getElementById('info-box1');
const tooltipParentRightPosition = oltipParent.getBoundingClientRect().right;
const windowWidth = document.documentElement.clientWidth;
const tooltipInitPosition = -tooltip.getBoundingClientRect().width;
if ((tooltipParentRightPosition - windowWidth) >= tooltipInitPosition) {
tooltip.style.right = tooltipParentRightPosition - windowWidth + 'px';
}
});
}
<div id = "grid-container" class = "container">
<div id = "product1" class = "products">
<label for = "one">
<input id = "one" type = "checkbox" name = "wobblers" value = "one">
</label>
<img>
<div class = "btn-wrapper">
<button id = "product1-info" class = "btn btn-info">info</button>
<div class = "info-box" id = "info-box1"></div>
</div>
</div>
</div>
И несколько изменений в CSS
.btn-wrapper {
display: inline-block;
position: relative;
}
.info-box {
visibility: hidden;
width: 80px;
height: 60px;
background: grey;
position: absolute;
top: -60px;
right: -80px;
border-radius: 10% 10% 10% 1%;
}
#product1-info:hover + #info-box1 {
visibility: visible;
}
Надеюсь, это вам поможет)
Вот окончательное решение:
Javascript:
const hovered = document.querySelectorAll('.product-info');
Array.prototype.forEach.call(hovered, function (item) {
item.addEventListener("mouseover", changeElementPosition);
});
function changeElementPosition() {
const tooltipParent = document.querySelectorAll(".product-info");
const tooltip = document.querySelectorAll('.info-box');
for (let i = 0; i < tooltipParent.length; i++) {
console.info(tooltip[i]);
const tooltipParentRightPosition = tooltipParent[i].getBoundingClientRect().right;
const windowWidth = document.documentElement.clientWidth;
const tooltipInitPosition = -tooltip[i].getBoundingClientRect().width;
if ((tooltipParentRightPosition - windowWidth) >= tooltipInitPosition) {
tooltip[i].style.right = tooltipParentRightPosition - windowWidth + 'px';
}
else{
tooltip[i].style.right = "-80px";
}
}
window.addEventListener("resize", () => {
const tooltipParent = document.querySelectorAll(".product-info");
const tooltip = document.querySelectorAll('.info-box');
for (let i = 0; i < tooltipParent.length; i++) {
const tooltipParentRightPosition = tooltipParent[i].getBoundingClientRect().right;
const windowWidth = document.documentElement.clientWidth;
const tooltipInitPosition = -tooltip[i].getBoundingClientRect().width;
if ((tooltipParentRightPosition - windowWidth) >= tooltipInitPosition) {
tooltip[i].style.right = tooltipParentRightPosition - windowWidth + 'px';
}
else{
tooltip[i].style.right = "-80px";
}
}
});
}
CSS:
.btn-wrapper {
display: inline-block;
position: relative;
}
.info-box{
visibility: hidden;
width:80px;
height:60px;
background:grey;
position:absolute;
top: -60px;
right: -80px;
border-radius:10% 10% 10% 1%;
}
.product-info:hover .info-box {
visibility: visible;
}
HTML:
<div id = "product4" class = "products">
<input id = "four" type = "checkbox" name = "wobblers" value = "four">
<label for = "four">
<img id = "four" src = "https://cdn.shopify.com/s/files/1/1557/0907/products/product-image-507865262.jpg?v=1527268422" alt = "rapala">
<div class = "btn-wrapper">
<button id = "product4-info" class = "product-info btn btn-info">info
<div class = "info-box" id = "info-box4"></div>
</button>
</div>
</label>
</div>
Спасибо, сработало! В строке 13 была опечатка (код javascript), но все в порядке, я нашел ее, и после этого мне нужно было использовать только имена классов для кнопок и полей описания и перебирать список узлов, и если фактический элемент расширяется дальше от правой стороны окна просмотра он меняет свое положение. Вы ответили, что очень помогло, мне потребовалось бы много времени, чтобы выяснить, какие методы использовать для получения параметров моих элементов.