下面是使用JS的快速解決方案。沒有看到任何JS/HTML,因此你需要將它適應任何代碼如下:
var imgboxes = document.querySelectorAll('.imgbox');
imgboxes.forEach(function (imgbox) {
var rect = imgbox.getBoundingClientRect(),
screen_width = document.body.clientWidth,
popup_width = <<POPUP_CONTENT_WIDTH>>;
if (rect.right + popup_width > screen_width) {
imgbox.classList.add('to_left');
}
});
,然後改變你的CSS像這樣的彈出:
.imgbox:hover .imgbox_content{
display: block;
z-index:2;
width:600px;
border-radius: 1%;
border:1px solid gray;
-webkit-transition: 1s;
position:absolute;
background: black;
color:white;
}
imgbox:hover .imgbox_content.to_left {
/* this assumes you've got a position:relative item wrapping the imgbox and that .imgbox_content is a child */
right: 0;
}
爲了獲得更完整,你也可以處理屏幕大小:
window.addEventListener('resize', calculate_pos_imgboxes)
var calculate_pos_imgboxes = function() {
var imgboxes = document.querySelectorAll('.imgbox');
imgboxes.forEach(function (imgbox) {
var rect = imgbox.getBoundingClientRect(),
screen_width = document.body.clientWidth,
popup_width = <<POPUP_CONTENT_WIDTH>>;
if (rect.right + popup_width > screen_width) {
imgbox.classList.add('to_left');
} else {
imgbox.classList.remove('to_left');
}
});
}
calculate_pos_imgboxes();
非常感謝你@ Josh-burgess!我正在使用Angular 2,仍然在尋找如何在其中完成同樣的事情。 – shanke
@shanke如果有幫助,請將其標記爲將來有人遇到來自Google的類似問題的答案。謝謝! –