从页面中的兄弟元素中滚动一个元素

Scrolling one element from a sibling element within a page

本文关键字:元素 一个 滚动 兄弟      更新时间:2023-09-26

必须在iframe内滚动另一个iframe。滚动位置是标签的href属性。我可以找到元素#ftoc,其中包含我想要滚动的文档,一个位于同一域的html文件。

我有这段代码来做滚动

$('#cfrench', window.parent.parent.document).contents().find('#ftoc').contents().find('body').animate({scrollTop: $('a[href="'+text+'"]').offset().top-1},500);

.contents().find('body')似乎有问题。滚动到那个href的正确方法是什么?谢谢。

看看这个版本

var elementClicked = $('a[href="' + text + '"]');
var destination = $(elementClicked).offset().top;
var $frame = $('#cfrench', window.parent.parent.document).contents().find('#ftoc').contents();
$frame.find("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination - 20 }, 500);

注。我无法检查代码,因为我不了解细节。

2.0版本:)(工作解决方案)

main.html

<iframe id="frame1" src="page-1.htm"></iframe>
<iframe id="frame2" src="page-2.htm"></iframe>

页面- 1. - html

<head>
    <title></title>
    <style type="text/css">
        #anchor { margin-top:400px; display:block; }
    </style>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#scroller').click(function () {
                var $frame = $(window.parent.document).find('#frame2').contents();
                var $anchor = $frame.find('#anchor');

                var destination = $anchor.offset().top;
                console.log(destination);
                $frame.find("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination - 20 }, 500);
                return false;
            });
        });
    </script>
</head>
<body>
    Page 1
    <a id="scroller" href="#">Scroll iframe</a>
</body>

页面- 2. - html

<head>
    <style type="text/css">
        #anchor { margin:400px 0; display:block; }
    </style>
</head>
<body>
    Page 2
    <a id="anchor" href="anhor.html">Anchor</a>
</body>