创建一个“弹出”迷你页面

时间:2011-04-30 23:25:09

标签: javascript popup lightbox

问题

我打算制作一个类似灯箱的项目页面。我希望在用户点击图像的地方有它,它会显示一个div,其中包含一个带有段落,图像以及我想要放入其中的任何其他内容的文章。它基本上是一个可滚动的文章,悬停在原始页面上,用户可以关闭该文章再次查看项目页面。我不想强迫用户在进入图库页面时下载每篇文章。

请求

有没有办法从存储在服务器上的html文件中提取这样的小文章?有没有更好的方法来解决这个问题?

-edit - 我宁愿不使用jQuery或任何其他JavaScript库。本网站将提供给Javascript课程,所以我希望这一切都是正常的javascript代码。此外,我宁愿学习jQuery如何做到这一点,而不是盲目地使用它。

提前致谢!

3 个答案:

答案 0 :(得分:1)

这是纯JavaScript中的简单灯箱,从指定的URL加载其内容。它没有优雅地处理错误,如果它在IE中工作,它只在较新的版本中。

由于它正在获取目标页面的HTML并将其直接插入到文档中,因此如果URL指向完整的HTML页面,它可能会表现得很奇怪。如果网址仅指向HTML代码段(无<html><body>代码),则效果最佳。

var lightboxPage = function(path) {
  // fetches content from a specified path and displays it in a lightbox

  var backdrop = document.createElement("div");
  var content = document.createElement("div");

  content.innerText = "Loading...";

  // use AJAX to load the content from the page
  var request = new XMLHttpRequest();

  request.open("GET", path, false);

  var handleAjaxEvent = function() {
    // this function is called multiple times during the AJAX request.
    // a state of 4 means that the request has completed.
    if (request.readyState == 4) {
        content.innerHTML = request.responseText;
    }
  }

  request.onreadystatechange = handleAjaxEvent;
  request.send();

  backdrop.style.position = "fixed";
  backdrop.style.top = 0;
  backdrop.style.height = "100%";
  backdrop.style.left = 0;
  backdrop.style.width = "100%";
  backdrop.style.zIndex = 500;
  backdrop.style.background = "black";
  backdrop.style.opacity = 0.8;

  content.style.position = "fixed";
  content.style.top = "10%";
  content.style.height = "80%";
  content.style.left = "10%";
  content.style.width = "80%";
  content.style.zIndex = 600;
  content.style.border = "none";
  content.style.overflow = "auto";
  content.style.background = "white";

  document.body.appendChild(backdrop);
  document.body.appendChild(content);

  var removeLightbox = function() {
    document.body.removeChild(backdrop);
    document.body.removeChild(content);
  }

  // remove the lightbox when people click on the backdrop
  backdrop.addEventListener("click", removeLightbox)
};

// example usage
lightboxPage("test.html");

Mozilla's AJAX tutorial也可能对您有用。

答案 1 :(得分:0)

查看jQuery和FancyBox。我认为这将涵盖它。 http://fancybox.net/

答案 2 :(得分:0)

相关问题