现在,我有了这段代码,可以在Chrome上正常工作。
// scroll on page load
scrollWindowToElement(document.querySelector('.something'))
/**
* Scroll to specific element.
*/
function scrollWindowToElement(el) {
let pos = getTop(el)
window.scrollTo(0, pos)
document.body.scrollTo(0, pos)
}
/**
* Get top position of an element.
*/
function getTop(el) {
let top = 0
while (el && !isNaN(el.offsetTop)) {
top += el.offsetTop - el.scrollTop
el = el.offsetParent
}
return top
}
<div class='onething'>hello</div>
<div class='something'>world</div>
<div class='anotherthing'>foo</div>
问题是,为什么它不能在Safari(台式机或移动设备)和其他浏览器上运行,以及如何使其在所有 modern 浏览器中正常运行(不使用jQuery,即使用香草JavaScript)
作为切线笔记,如果这很重要,元素和document.body都可以与opacity: 0
一起使用,但是与display: none
无关,因此在Chrome中至少可以正常工作。
我需要做类似this的事情吗?
答案 0 :(得分:0)
您的代码有一些问题。
首先,您应使用#!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from mainw import Ui_Form
#Subscriber
from std_msgs.msg import MultiArrayDimension
from std_msgs.msg import Int32MultiArray
import rospy
class main(QWidget, Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
for i in range(0,20):
for j in range(0,20):
self.tableWidget.setItem(i, j, QTableWidgetItem())
def callback(msg):
for i in range(0,19):
for j in range(0,19):
if(msg.(i+j)==1)
self.tableWidget.item(i,j).setBackground(QColor(170, 0, 0))
else if(data.data==2)
self.tableWidget.item(i, j).setBackground(QColor(170, 0, 0))
def TwoDMap():
rospy.init_node('TwoDMap', anonymous=True)
rospy.Subscriber("array", Int32MultiArray, callback)
rospy.spin()
if __name__ == '__main__':
TwoDMap()
app=QApplication(sys.argv)
window =main()
window.show()
app.exec_()
事件,方法是设置load
或通过添加事件侦听器,如下所示:
window.onload
第二,您的滚动功能只需要使用 // scroll on page load
window.addEventListener('load', function() {
scrollWindowToElement(document.querySelector('.something'));
});
window.scrollTo
第三,您的 /**
* Scroll to specific element.
*/
function scrollWindowToElement(el) {
let pos = getTop(el);
window.scrollTo(0, pos);
}
实现可能没有给您正确的位置。最简单的方法:
getTop
还请注意,此代码仅用于更改页面加载时的滚动位置。
对于页面刷新,许多浏览器倾向于记住旧的滚动位置并在窗口加载后恢复(通过强制更改)它。因此,如果要覆盖页面刷新还原滚动行为,则必须在加载事件侦听器中使用延迟 /**
* Get top position of an element.
*/
function getTop(el) {
return window.scrollY + el.getBoundingClientRect().top;
}
的调用。测试scrollWindowToElement
的一些合理值。在大多数情况下,延迟100毫秒左右应该可以很好地工作。