我想用JavaScript添加CSS样式:" padding"," background"和" border"对于用户点击的图像,当用户再次点击该图像时,将删除高亮效果。
var imagesProp = {
'padding': '3px',
'backgroundColor': '#eded01',
'borderSize': '1ps',
'borderStyle': 'dashed',
'borderColor': '#0001fe'
};
function highlightimages() {
var allimages = document.getElementsByid('images');
//How do i start from here
}
答案 0 :(得分:1)
var imagesProp = {
'padding': '3px',
'backgroundColor': '#eded01',
'borderSize': '1ps',
'borderStyle': 'dashed',
'borderColor': '#0001fe'
};
function highlightImages() {
//You do not use getElementsByid but getElementsByTagName
var allimages = document.getElementsByTagName('img');
var nrallimgs = allimages.length;
// traverses the <img> elements, and register onclick to each one
// else, apply the properties defined in $imagesProp
for(i=0; i<nrallimgs; i++) {
allimages[i].onclick=function() {
if(this.style.borderStyle == imagesProp.borderStyle) {
this.style.padding = 'auto';
this.style.background = 'none';
this.style.border = 'none';
}
else {
this.style.padding = imagesProp.padding;
this.style.backgroundColor = imagesProp.backgroundColor;
this.style.borderSize = imagesProp.borderSize;
this.style.borderStyle = imagesProp.borderStyle;
this.style.borderColor = imagesProp.borderColor;
}
}
}
}
// calls the highlightImages() function to apply the effect
highlightImages();
答案 1 :(得分:0)
创建一个css类
highlighted {
padding: '3px';
backgroundColor: '#eded01';
borderSize: '1ps';
borderStyle: 'dashed';
borderColor: '#0001fe'
}
使用jQuery:
var $element = $('#elementid');
$element.click(function () {
$(this).toogleClass('highligted');
});