问题
I'm trying to implement a simple thing in my page using jQuery and Fancybox, but I can't put my code to work.
I need create a code that when user click in any part of the page, Fancybox opens a modal.
Currently, my code is the following:
<script>
$(document).ready(function(){
$(document).click(function(e){
$.fancybox.open([{
href: '/welcome',
title: 'Welcome to Our Website!'
}],
{
width: 800,
height: 600
});
});
});
</script>
For me the code is nice, but when I go to this page and click in a lot of parts of the page, nothing happens. Note: the console don't display any error messages, so, what I'm doing wrong?
回答1:
If you want fancybox to open when user clicks anywhere in your page after page load (and before they can interact with the page itself) then try
jQuery(document).ready(function ($) {
// add fancybox class to body on page load
$("body").addClass("fancyopen");
// bind click to body
$(".fancyopen").on("click", function () {
$.fancybox([{
href: "/yourpage.html",
title: "welcome to our website"
}], {
width: 300,
height: 200,
type: "iframe",
afterShow: function () {
$(".fancybox-wrap").on("click", function (event) {
event.stopPropagation(); // so you can click fancybox without calling it again
});
},
afterClose: function () {
$(".fancyopen").unbind("click").removeClass("fancyopen"); // now you can interact with the page
}
}); // fancybox
}); // on
}); // ready
See JSFIDDLE
来源:https://stackoverflow.com/questions/19618209/fancybox-when-click-in-any-part-of-page-open-fancybox