2017-06-19 57 views
0

我在一個網站上工作,雖然鼠標懸停在DVD上顯示的細節就像您在圖片1中看到的,但是,它不適用於放置在屏幕右側的那些DVD,如圖2所示,內容被切碎了。如何在css中對齊彈出的div方向?

如何讓它自動選擇顯示內容的方向?就像這張DVD靠近正確的屏幕一樣,在左邊顯示內容?

非常感謝!

.imgbox .imgbox_content{ 
    display: none; 
} 

.imgbox:hover .cover{ 
    display: none; 
} 

.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; 
} 

Normal

Error

回答

1

下面是使用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(); 
+0

非常感謝你@ Josh-burgess!我正在使用Angular 2,仍然在尋找如何在其中完成同樣的事情。 – shanke

+0

@shanke如果有幫助,請將其標記爲將來有人遇到來自Google的類似問題的答案。謝謝! –

0

做到這一點,最簡單的方法是隻迫使你的彈出窗口出現在屏幕的中央。你可以使用position:absolute來做到這一點。但是,如果您想將彈出窗口綁定到該項目的位置 - 那麼您必須進行一些計算。

它看起來像這樣。

  1. 獲取彈出窗口的寬度。
  2. 獲取目標左邊緣到屏幕右邊緣的距離。
  3. 比較1和2
  4. 如果分辨率爲<寬度,則向左偏移。否則,向右偏移。

此代碼看起來像(使用jQuery)。

var padding = 20; 
var elem = $(yourpopup); 
var popupwidth = elem.width(); 
var position = p.position(); 
var dist = position.left - popupwidth; 
    // if the popup is wider than distance to edge plus padding, then offset margin using negative value. 
    if (dist < popupwidth){ 
    elem.css('margin-left', "'-" + popupwidth + padding + "px'"); 
}