我有一个包含长内容的 JSF/Primefaces 页面,由滚动条处理,还有一个包含长内容和滚动条的对话框。 该对话框包含一个按钮,我想将对话框内容滚动到对话框内的某个组件(几乎在其底部),但是如果我使用
PrimeFaces.current().scrollTo("component");
滚动会影响底部页面,而不是对话框内部。
通过阅读其他问题我尝试通过将脚本直接放在按钮onclick上来用JQuery实现效果
$('#dialog').animate({scrollTop: $('#dialogForm\\:panelDialog').offset().top},'slow');
但它不起作用。
以下是最小(非)工作示例的文件。
XHTML 页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<p:commandButton value="Basic" type="button" onclick="PF('dialogVar').show();" />
<p:commandButton value="Scroll" actionListener="#{testCBean.onClick()}" />
<p:panel>
<ui:repeat var="item" value="#{testCBean.tableRows}">
<div>
#{item}
</div>
</ui:repeat>
</p:panel>
<p:outputPanel id="panel">
scroll destination
</p:outputPanel>
<p:dialog id="dialog" header="Basic Dialog" widgetVar="dialogVar" minHeight="40" height="500">
<h:form id="dialogForm">
<p:commandButton value="Scroll" actionListener="#{testCBean.onClickDialog()}" />
<ui:repeat var="item" value="#{testCBean.tableRows}">
<div>
#{item}
</div>
</ui:repeat>
<p:outputPanel id="panelDialog">
scroll destination
</p:outputPanel>
</h:form>
</p:dialog>
</h:body>
</html>
bean :
package controller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.primefaces.PrimeFaces;
@Named
@SessionScoped
public class TestCBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<String> tableRows;
@PostConstruct
public void init() {
tableRows = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
tableRows.add("Test");
}
}
public List<String> getTableRows() {
return tableRows;
}
public void setTableRows(List<String> tableRows) {
this.tableRows = tableRows;
}
public void onClick() {
PrimeFaces.current().scrollTo("panel");
}
public void onClickDialog() {
PrimeFaces.current().scrollTo("dialogForm:panelDialog");
// PrimeFaces.current().executeScript("$('#dialog').animate({scrollTop: $('#dialogForm\\:panelDialog').offset().top},'slow');");
}
}
最佳答案
我找到了一种通过 JQuery 执行此操作的方法,即使用以下脚本:
function dialogScroll(dialogId, elementId) {
$('#' + dialogId).find('.ui-dialog-content').first().animate({scrollTop: $('#' + elementId).offset().top},'slow');
}
第一个参数是对话框的 id,它用作查找要滚动到的元素的容器,其 id 作为第二个参数传递。
然后可以在按钮 onclick 中直接调用该函数,或者在 java bean 方法中以如下方式调用:
PrimeFaces.current().executeScript("dialogScroll('dialog', 'dialogForm\\\\:panelDialog');");
注意元素 id 中的转义,如果它包含“:”,则这是必要的
关于javascript - 单击按钮时滚动到对话框内的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53794673/