让我们构建一个小模块,用来在一个JavaScript文件中包含一些jQuery函数。首先,我们需要一个用例。嗯,使用JavaScript代码来控制区块,如何?区块在Drupal中是很有用的:它们可以为你显示你的登录状态,告诉你站点的新进用户或者在线用户,提供有用的导航。但是有时候,你只想关注页面的内容。如果在默认的情况下把区块隐藏,只有当你想要查看它们的时候才将其显示出来,这样不也不错么?下面的模块实现了这一点,它使用jQuery来对左右边栏区域中的区块进行标识和隐藏,并提供了一个有用的按钮用来将区块重新显示出来。
下面是sites/all/modules/custom/blockaway.info:
; $Id$
name = Block-Away
description = Uses jQuery to hide blocks until a button is clicked.
package = Pro Drupal Development
core = 6.x
而下面是sites/all/modules/custom/blockaway.module:
<?php
// $Id$
/**
* @file
* Use this module to learn about jQuery.
*/
/**
* Implementation of hook_init().
*/
function blockaway_init() {
drupal_add_js(drupal_get_path('module', 'blockaway') .'/blockaway.js');
}
这个模块的全部工作就是包含以下的JavaScript文件,我们可以将它放在sites/all/modules/custom/blockaway/blockaway.js:
// $Id$
/**
* Hide blocks in sidebars, then make them visible at the click of a button.
*/
if (Drupal.jsEnabled) {
$(document).ready(function() {
// Get all div elements of class 'block' inside the left sidebar.
// Add to that all div elements of class 'block' inside the
// right sidebar.
var blocks = $('#sidebar-left div.block, #sidebar-right div.block');
// Hide them.
blocks.hide();
// Add a button that, when clicked, will make them reappear.
$('#sidebar-left').prepend('<div id="collapsibutton">Show Blocks</div>');
$('#collapsibutton').css({
'width': '90px',
'border': 'solid',
'border-width': '1px',
'padding': '5px',
'background-color': '#fff'
});
// Add a handler that runs once when the button is clicked.
$('#collapsibutton').one('click', function() {
// Button clicked! Get rid of the button.
$('#collapsibutton').remove();
// Display all our hidden blocks using an effect.
blocks.slideDown("slow");
});
});
}
导航到“管理➤站点构建➤模块”,启用该模块,你以前可见的所有区块都消失了,被替换为了一个没有格式的按钮,如图17-5所示。
图 17-5. blockaway.module启用后,一个节点的显示
点击了这个按钮以后,区块将会使用一个幻灯效果显示出来,变成可见的,如图17-6所示。
图 17-6.点击了显示区块按钮以后,区块变成了可见的。
老葛的Drupal培训班 Think in Drupal