打开模态视图时禁用正文上的滚动

时间:2014-03-02 12:13:28

标签: javascript jquery html css

我发现了一个JQuery解决方案,在打开模态视图时禁用身体上的滚动,但我正在寻找一个Javascript解决方案,任何人都可以告诉我转换为JS将如何:

$(function () {
var $body = $(window.document.body);

function bodyFreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('overflow', 'hidden');
    $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}

function bodyUnfreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
    $body.css('overflow', 'auto');
}

$('.modal').hide()

$('.longcontent.main button').click(function () {
    $('.modal').show()
    bodyFreezeScroll()
})
$('.modal button').click(function () {
    $('.modal').hide()
    bodyUnfreezeScroll()
})})

http://jsfiddle.net/ngwhk/

1 个答案:

答案 0 :(得分:0)

我能想出的最好的香草js是这样的:

http://jsfiddle.net/ngwhk/23/

var $body = window.document.body;
var $modal = document.getElementsByClassName("modal")[0];
var aOpenButtons = document.getElementsByClassName("open-modal");
var aCloseButtons = document.getElementsByClassName("close-modal");


function bodyFreezeScroll($obj) {
    $body.style.overflow = "hidden";
    $body.style.marginRight = getScrollBarWidth()+"px";
}

function bodyUnfreezeScroll() {
    $body.style.overflow = "auto";
    $body.style.marginRight = "auto";
}


function showModal(){
    $modal.classList.add("visible");
    $modal.classList.remove("hide");
}

function hideModal(){
    $modal.classList.add("hide");
    $modal.classList.remove("visible");
}


for(var i = 0, a=aOpenButtons.length; i<a; i++){
   aOpenButtons[i].addEventListener("click", function(){
    showModal();
    bodyFreezeScroll();
    }, false); 
}

for(var i = 0, a=aCloseButtons.length; i<a; i++){
   aCloseButtons[i].addEventListener("click", function(){
    hideModal();
    bodyUnfreezeScroll();
    }, false);
}

function getScrollBarWidth() {
    /* found here: https://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes */
  var inner = document.createElement('p');
  inner.style.width = "100%";
  inner.style.height = "200px";

  var outer = document.createElement('div');
  outer.style.position = "absolute";
  outer.style.top = "0px";
  outer.style.left = "0px";
  outer.style.visibility = "hidden";
  outer.style.width = "200px";
  outer.style.height = "150px";
  outer.style.overflow = "hidden";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};

<强>更新
我在这里找到了一种测量滚动条宽度的方法:How can I get the browser's scrollbar sizes?

由于过渡似乎没有被触发,当我改变样式或添加类时(请更正此,如果你知道一种方法)我为此添加了关键帧动画。

@keyframes show {
  0%   { top: -100%; }
  100% { top: 0; }
}

@keyframes hide {
  0%   { top: 0%; }
  100% { top: -100%; }
}