nik*_*las 8 javascript wordpress reactjs wordpress-gutenberg gutenberg-blocks
如何在wordpress gutenberg编辑器中将新插入的块滚动到视图中?
我正在创建块
const nextBlock = createBlock( 'core/paragraph' );
wp.data.dispatch( 'core/editor' ).insertBlock( nextBlock );
//scroll the block into the view
Run Code Online (Sandbox Code Playgroud)
我还看到古登堡(Gutenberg)dom-scroll-into-view
像在这里那样使用软件包。
他们的文件说:
var scrollIntoView = require('dom-scroll-into-view');
scrollIntoView(source,container,config);
Run Code Online (Sandbox Code Playgroud)
但是如何使它在我的情况下起作用,如何获取源和容器DOM元素?
就我而言,如何获取源 DOM 元素和容器 DOM 元素?
它实际上很简单..只需用于document.querySelector()
获取块节点,然后wp.dom.getScrollContainer()
获取该节点的容器:
const nextBlock = wp.blocks.createBlock( 'core/paragraph' );
wp.data.dispatch( 'core/editor' ).insertBlock( nextBlock );
const source = document.querySelector( '[data-block="' + nextBlock.clientId + '"]' );
const container = wp.dom.getScrollContainer( source );
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
/**
* External dependencies
*/
import scrollIntoView from 'dom-scroll-into-view';
/**
* WordPress dependencies
*/
import { createBlock } from '@wordpress/blocks'; // wp.blocks.createBlock
import { dispatch } from '@wordpress/data'; // wp.data.dispatch
import { getScrollContainer } from '@wordpress/dom'; // wp.dom.getScrollContainer
function getBlockDOMNode( clientId ) {
return document.querySelector( '[data-block="' + clientId + '"]' );
}
const nextBlock = createBlock( 'core/paragraph' );
dispatch( 'core/editor' ).insertBlock( nextBlock );
const source = getBlockDOMNode( nextBlock.clientId );
const container = source ? getScrollContainer( source ) : null;
if ( source && container ) {
scrollIntoView( source, container );
}
Run Code Online (Sandbox Code Playgroud)
要测试import
ed scrollIntoView()
,请尝试以下操作:
function scrollBlockIntoView( block ) {
const source = getBlockDOMNode( block.clientId );
const container = source ? getScrollContainer( source ) : null;
if ( source && container ) {
console.log( source, container );
scrollIntoView( source, container );
}
}
window.scrollBlockIntoView = function( block ) {
scrollBlockIntoView( block || {} );
};
Run Code Online (Sandbox Code Playgroud)
然后从浏览器控制台运行以下命令:
scrollBlockIntoView( wp.data.select('core/editor').getBlocks()[1] )
Run Code Online (Sandbox Code Playgroud)
但请确保编辑器中至少有两个块 - 例如,一个包含较长内容的段落和一个图像块。
已在 Chrome (Windows 10) 上进行尝试和测试。
归档时间: |
|
查看次数: |
374 次 |
最近记录: |