使用复选框更改背景图像宽度
Change background image width with checkbox?
我有一个简单的Chrome扩展,注入一些html到一个游戏网页,让用户自定义网页的背景图像。它使用setlocalstorage存储图像的URL,这样当他们返回游戏时,自定义背景图像仍然在那里。我已经包含了一些CSS来强制图像适应浏览器窗口的宽度。这满足了大多数用户,但也有一些用户要求我允许他们关闭宽度匹配功能。我想做的是添加一个复选框,允许用户关闭宽度调整。
我在想一些"如果框被选中,将这个类应用到body标签"之类的东西,但是,我似乎不能弄清楚。
如果有人能告诉我如何做到这一点,我真的很感激!将onchange事件监听器附加到复选框上,用于检查复选框元素的'checked'值并添加/删除该类:
yourCheckboxElement.addEventListener('change', function(e){
document.body.classList[this.checked ? "add" : "remove"]("someClass");
/* save value of this.checked to localStorage here */
});
jsFiddle示例:http://jsfiddle.net/8RC2m/1/
当复选框被标记时改变css:
$("#new").click(function() {
if (this.checked){
$(this).closest('p').addClass('white');
} else {
$(this).closest('p').removeClass('white');
}
});
添加样式:
.white {
color: white;
}
那可能对你有用,不是吗?
另外$(":checkbox").attr("autocomplete", "on");
将宽度调整代码包装在像width-adjustment
这样的css类中。然后尝试这样做:
if ($('#IdOfYourCheckBox').is(":checked") == true){
$("#ElementToChange").removeClass('width-adjustment');
}
你只要求JavaScript,所以我将避免使用jQuery,尝试这样做:
var b = document.getElementsByTagName("body")[0];
if (document.getElementById('checkbox-id').checked){
b.className +=" yourclass";
}
希望有所帮助
您可以使用这个脚本来检查复选框是否被选中。
(function( $ ){
$.fn.check = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if ($(this).attr('checked')) {
handler.call(this);
$(this).closest('p').addClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', true);
$(this).change();
$(this).closest('p').addClass('white');
});
}
};
$.fn.uncheck = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if (!$(this).attr('checked')) {
handler.call(this);
$(this).closest('p').removeClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', false);
$(this).change();
$(this).closest('p').removeClass('white');
});
}
};
})( jQuery );
相关文章:
- 在视频和图像背景之间切换
- 带有图像背景的简单倒数计时器
- 无法设置图像背景图像
- 使用jQuery的透明图像背景
- 加快图像背景的页面加载速度
- HTML5 画布 - 如何在图像背景上画一条线
- IE8(Javascript和CSS)中带有拉伸BG的渐变图像背景
- 需要有关所选图像背景颜色的帮助.并将背景去除到所选择的其他图像
- 透明图像背景html5画布
- 你能帮我最大化我的图像背景吗
- 实现基于浏览器宽度的大图像背景拉伸的最简单方法
- Javascript改变图像/背景图像不工作
- 使悬停时的图像背景变暗,不影响文字
- 如何在javascript中扩展画布图像's背景并转换为文件对象
- JQuery移动设置图像背景与CSS
- 向图像(背景图像)添加超链接
- 课程互动360视频/图像背景在html5引导
- 在jQM中,为页面设置全屏CSS图像背景的正确/正确/实际方法是什么?
- 链接上随机图像背景
- 在JavaScript上设置图像背景形状