如何修改Magnific Popup弹窗代码,实现点击图片跳转网页链接?
Solution for Adding Clickable Link to Magnific Popup Image
Hey there! I've got you covered. To make the auto-popup image redirect to a specified URL when clicked, you can use one of these two straightforward approaches:
Method 1: Use Inline Content (Most Flexible)
This method lets you wrap the image in an <a> tag by switching the popup type to inline, which gives you full control over the popup content:
$(document).ready(function() { var delay = 5000; // 5 seconds var targetUrl = "https://your-target-url.com"; // Replace with your actual link setTimeout(function(){ $.magnificPopup.open({ items: { // Wrap your image in a clickable link; use mfp-hide to hide the container initially src: `<div class="mfp-hide"> <a href="${targetUrl}" target="_blank"> <img src="img/bg-corporate-20-2.jpg" alt="Corporate Popup"> </a> </div>`, type: "inline" }, callbacks: { open: function() { // Optional: Adjust image styling to fit the popup properly $(".mfp-content img").css({ maxWidth: "100%", height: "auto", cursor: "pointer" // Visual cue that the image is clickable }); } } }); }, delay); });
Why this works:
- The
inlinetype lets you inject custom HTML, so we’re directly adding a link around the image. - The
mfp-hideclass ensures the container div isn’t visible on your page before the popup triggers. - Adding
target="_blank"opens the link in a new tab (remove it if you want the link to open in the same tab).
Method 2: Bind Click Event to Image Type (Keep Native Popup Styling)
If you prefer to stick with the native image type of Magnific Popup, you can attach a click event to the popup image using callbacks:
$(document).ready(function() { var delay = 5000; // 5 seconds var targetUrl = "https://your-target-url.com"; // Replace with your actual link setTimeout(function(){ $.magnificPopup.open({ items: { src: "img/bg-corporate-20-2.jpg", type: "image" }, callbacks: { open: function() { // Bind click event to the popup image $(".mfp-img").on("click", function() { window.location.href = targetUrl; // Use this line instead to open in new tab: // window.open(targetUrl, "_blank"); }); // Add pointer cursor to indicate clickability $(".mfp-img").css("cursor", "pointer"); }, close: function() { // Remove the click event to avoid duplicate bindings on repeated popups $(".mfp-img").off("click"); } } }); }, delay); });
Why this works:
- The
opencallback runs when the popup loads, so we can safely target the.mfp-imgelement (Magnific Popup’s default class for the popup image). - We remove the click event in the
closecallback to prevent multiple event bindings if the popup triggers again.
Pick whichever method fits your needs better—both will get the job done!
内容的提问来源于stack exchange,提问作者Minh Hải
相关产品推荐
相关产品推荐

