簡體   English   中英

將 css:target selector 與 url hash 參數組合以顯示模態時出現問題

[英]Problems when combining css :target selector with url hash parameters for showing a modal

我的 javascript 和 css 知識相當有限。 我想我錯過了一些關於何時以及如何應用 css 以及頁面加載與異步 javascript 相結合如何工作的一些細節。

這是有效的:我有一個僅 css 模態,當我的模態( view )的 id 與 url( #view )中的 hash 匹配時顯示。 我用它來顯示圖像(它是所有圖像的相同模態 div,並且實際圖像 src 通過添加到模態錨鏈接的事件偵聽器進行更新)。 這工作正常。

這是有效的:我想擴展它,因此我可以通過提供 url 作為 hash 參數來直接鏈接到已經打開的彈出窗口。 example.com/#view=imageUrl Just opening this will not make the css selector :target match, since it now contains the view, but if I split this off by checking var hash = window.location.hash.substr(1); 我可以將 url 與錨分開,然后使用:

window.history.pushState("", "", window.location.href.split('=')[0]);
updateModal(imageUrl)

其中updateModal將圖像的源設置為分離的 url。 一切都很好,即站點打開時模式打開,並且其中的圖像來自 url。

這不起作用:現在我想,作為 hash 參數提供的圖像可能不再存在,所以我只想在提供有效圖像時顯示模態,否則 go 到主頁。 我創建了一個虛擬圖像元素,嘗試從imageUrl加載圖像並將分割和更新位移動到虛擬圖像的 onload 方法,如下所示:

dummyImage.onload = function () {
    window.history.pushState("", "", window.location.href.split('=')[0])
    updateModal(imageUrl)
}

如果我這樣做,模態不會顯示。 css 沒有申請,這是為什么?

我還嘗試自己更改模態的可見性:

dummyImage.onload = function () {
    window.history.pushState("", "", window.location.href.split('=')[0])
    updateModal(imageUrl)
    var myModal = document.getElementById('view')
    myModal.style.display = 'flex'
    myModal.style.visibility = 'visible'
}

這使得模態出現,但似乎添加了一種不再被 css 覆蓋的樣式。 具體來說,當我單擊模態的關閉鏈接時,它只是轉到不同的錨#noname url 更改,css :target選擇器應該不再匹配,但模態不再關閉。 為什么 css 不再適用?

閱讀下面的鏈接,我相信這是一個錯誤,並且在使用 pushState 更改 url 時,頁面加載后不會重新評估目標選擇器。 我將通過始終顯示模態來解決此問題,如問題中的第二個工作示例中一樣,並使用后備圖像和消息來提醒用戶該圖像不再可用(我可以使用dummyImage.onerror觸發此更新)。

如果有人知道更好的解決方案或解決方法,我仍然有興趣學習!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM