显示类似于百度,在搜索框上边显示一行标签 , 点击一下标签 就把标签中的文字作为搜索的类别.
有点儿不同的项目里用jQuery创建图片加入形影属性 实现选择类别的功能
一:显示搜索门类
首页需要显示类别的位置:
<td id="articleTypeDiv"></td>
这是jQuery实现的,
1.循环所需的articleTypes在另一个js文件中定义(就是几组json数据)
2.创建标签后 用.attr方法添加属性
3.mouseover是jQuery的api 鼠标划过指定位置时时触发
4.划过时如果没有激活 则显示成激活状态
5.鼠标点击时触发, 先激活 ,点一下之后 如果原先就是激活状态就取消激活
6.鼠标划出时取消激活
$(function() {
var div = $('#articleTypeDiv');
for ( var type in articleTypes) { // articleTypes 的定义在下边
var articleType = articleTypes[type];
var img = $('<img>'); //创建标签
img.attr('src', articleType.src); //往里添加属性
img.attr('activeSrc', articleType.activeSrc);
img.attr('height', articleType.height);
img.attr('width', articleType.width);
img.attr('id', articleType.id);
img.attr('style', articleType.style);
img.attr('border', "0");
img.attr('alt', "");
img.bind('mouseover', function() { //鼠标划过指定位置时触发, 划过时如果没有激活 则显示成激活状态
var o = $(this);
if (o.attr('id') != activeId) {
o.attr('src', articleTypes[o.attr('id')].activeSrc);
}
});
img.bind('click', function() { //鼠标点击时触发, 先激活 ,点一下之后 如果原先就是激活状态就取消激活
var o = $(this);
o.attr('src', articleTypes[o.attr('id')].activeSrc);// 激活
if (activeId != '') {
if (o.attr('id') == activeId) {
o.attr('src', articleTypes[o.attr('id')].src);
activeId = '';
return;
} else {
document.getElementById(activeId).src = articleTypes[activeId].src;
}
}
activeId = o.attr('id');
});
img.bind('mouseout', function() {
var o = $(this);
if (o.attr('id') != activeId) {
o.attr('src', articleTypes[o.attr('id')].src);
}
});
div.append(img); //在div节点的末尾 ,补充上img
}
doSearchForm.reset(); //doSearchForm是搜索的提交表单
});
articletypes的定义,剩下的略
var articleTypes = {
'Java' : // 名称
{
id : 'Java',// id
style : 'cursor:hand;',// 样式,
src : 'images/top_02.gif',// 图片
activeSrc : 'images/top2_02.gif',// 被激活时的图片
width : 98,
height : 35
},
'Java web' : {
id : 'Java web',
style : 'cursor:hand;',
src : 'images/top_03.gif',
activeSrc : 'images/top2_03.gif',
width : 98,
height : 35
},
二:搜索表单获得类别
这个表单是搜索的提交表单
<s:form action="articleAction_doSearch" method="post" id="doSearchForm">
<table width="480" border="0" align="center" cellpadding="0"
cellspacing="0">
<s:hidden name="article.articleTypeName" id="articleTypeName"></s:hidden>
还是用js
<td width="113"><img src="images/so.GIF" width="109"
height="35" style="cursor: hand;" οnclick="doSearch()" /></td>
js检查一下输入的内容,然后帮表单提交到后台
function doSearch() {
var searchText = $.trim($('#searchStr').val());
if (!searchText) {
alert('请输入要搜素的内容');
return;
}
if (searchText.length > 255) {
alert('输入内容不能超过255个字符');
return;
}
doSearchForm.submit();
}