iframe子元素相对于父页面滚动条固定(iframe无滚动条,iframe固定高度有滚动条,两种情况)

一、当iframe自适应高度,无滚动条时候:

例如这样:

//随着父页面滚动条滚动定位“#qn-quc”他的位置固定在顶部
$(parent.window).scroll(function() {
    var scrollheight = parseInt($(parent.window).scrollTop());
    console.log(parseInt($(parent.window).scrollTop()))
    if (scrollheight >= 300) {
        $("#qn-quc").css({
            "position": "absolute",
            "top": parseInt($(parent.window).scrollTop()) - 120 + "px"

        });
    } else {
        document.getElementById("qn-quc").style = " ";
    }
});

或者这样:

 //题目按钮固定顶部
 $(window.parent.document).scroll(function() {
     var scrollheight = parseInt($(window.parent.document).scrollTop());
     if (scrollheight >= 300) {
         $("#qn-quc").css({
             "position": "absolute",
             "top": parseInt($(window.parent.document).scrollTop()) - 120 + "px"

         });
     } else {
         document.getElementById("qn-quc").style = " ";
     }
 });

二、当iframe页面存在滚动条就简单很多了

例如这样:

 var ie6 = document.all;
    var dv = $('#qn-quc'), st;
    dv.attr('otop', dv.offset().top); //存储原来的距离顶部的距离
    $(window).scroll(function () {
        st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
        if (st > parseInt(dv.attr('otop'))) {
        if (ie6) {//IE6不支持fixed属性,所以只能靠设置position为absolute和top实现此效果
        dv.css({ position: 'absolute', top: st });
        }
        else if (dv.css('position') != 'fixed') dv.css({ 'position': 'fixed', top: 0 });
        } else if (dv.css('position') != 'static') dv.css({ 'position': 'static' });
        });
//监听window滚动条位置

$(window).scroll(function () { var st = $(this).scrollTop(); console.log(st); });
原文地址:https://www.cnblogs.com/pengchengzhong/p/6781955.html