【问题标题】:Modal with link带链接的模态
【发布时间】:2019-01-08 23:53:47
【问题描述】:

我使用从 w3school 获得的模态,并对其进行了修改以将多个模态放在同一页面上。

我想知道我是否可以让这些模式生成自己的链接。 例子:我打开modal 4,页面链接会变成mywebsite.com/modal4

我使用的代码或多或少是这样的

JS

// Get the modal
var modal = document.getElementsByClassName('modal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal 
btn[0].onclick = function() {
    modal[0].style.display = "block";
}

btn[1].onclick = function() {
    modal[1].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
    modal[0].style.display = "none";
}

span[1].onclick = function() {
    modal[1].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

HTML

<h2>Modal Example1</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal1</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..1</p>
  </div>

</div>


<h2>Modal Example2</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal2</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

  <!-- Modal content -->
  <div class="modal2-content">
    <span class="close">×</span>
    <p>Some text in the Modal..2</p>
  </div>

</div>

【问题讨论】:

    标签: javascript html hyperlink


    【解决方案1】:

    您可以在打开模式时更改页面的当前 URL,如以下答案所示:Modify the URL without reloading the page。如果你去 mywebsite.com/modal4 加载模态,你可以写一些 js 逻辑来获取链接,看看它是否指向一个模态,然后打开那个模态。

    您可能需要编写一些后端代码来处理这样的链接,但是您可以尝试传递链接参数,然后使用 js 从链接字符串中解析出参数:How to get the value from the GET parameters?

    正如 JagdeeshKumar 在下面指出的,您还可以导航到 website.com/htmlpage.html#modal4,您可以使用 js 获取该位置并加载模态。见https://www.w3schools.com/jsref/prop_loc_hash.asp

    【讨论】:

    • 你可以使用 window.location.hash = 'something';您的 URL 将类似于 root/#modal4。
    • @JagdeeshKumar 这是个好主意,我会把它添加到我的答案中
    【解决方案2】:

    你可以使用

    您的网址将类似于 root/#modal4window.location.hash = 'something';

    【讨论】:

    • 我已经尝试过,但无法给出模态的链接 你有教程链接来教这个吗?我是新手
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多