Good face for Check Box in Jquery

本文介绍了一种使用jQuery实现自定义样式的复选框的方法,包括如何创建模仿复选框行为的链接,并通过添加和删除CSS类来改变其外观。此外,还介绍了如何将这种技术应用于实现类似iPhone风格的开关按钮。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://john.mcclumpha.org/javascript/Creating_custom_styled_checkboxes_with_jQuery/

http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html

javascript : Creating custom styled checkboxes with jQuery

Published: 1 years ago

Demonstration
.com .net .biz .info


For those of you who have been using my DHTML Effects using Javascript code, let me apologise. I have now been overtaken by the force known as jQuery! (Thanks Simon :P) If nothing else it's more compatible, widely supported with a huge development community and a lot more versatile than just a few animated effects. Anyhow, on with the show...

I got sick of the fact that checkboxes, like several other form elements, cannot be styled using css. As a result checkboxes in various browsers always appeared differently and were often enough to ruin a nice (otherwise) clean design. As such I came up with the following solution:

What we will do is create some links (<a href=""> tags) on a page which will represent the fake (styled) checkboxes. When these are clicked they will change in appearance (by adding a css class to them) and their hidden counterpart (the "real" checkbox) will have its value toggled accordingly.

Styling

I wanted a nice modern styling to my checkboxes, although you can easily give them any styling you want (if I get time I'll publish a heap of different samples and ways in which this can be used quite effectively).

I created an image containing both the unchecked and checked states of the checkbox: checkbox styling

The Objects

Next we need to create a link to use for our fake checkboxes:

<a href="#dotcom" class="fakecheck" id="fakedotcom">.com</a>

In this instance we want the text ".com" to be used as a "label" for the checkbox.

Now style the link as follows:

/* fake checkbox : unchecked (default/base) state */
.fakecheck {
	font: 12px Tahoma, Arial, Helvetica, sans-serif;
	text-decoration: none;
	outline: none;
	background: url(../images/checkbox.gif) no-repeat;
	height: 16px;
	width: 40px;
	display: block;
	float: left;
	padding: 1px 0px 0px 20px;
	color: #666666;
}
/* fake checkbox : hover state */
.fakecheck:hover {
	color:#0066FF;
	text-decoration: underline;
}
/* fake checkbox : checked state */
.fakechecked {
	background-position: left -25px;
}

You should now have a link which is the checkbox in it's unchecked state - note however that it doesn't work just yet.

Before we get things working, let's create the "real" checkbox (the one that will actually be used as part of the form) - this will of course be hidden at a later stage. We want this input to have the same id as the hash (#) in the link above, for consistency I use a matching name.

<input type="checkbox" name="dotcom" id="dotcom" />

The Code

Now the fun part... let's get this sucker working!

Firstly, let's create the code to toggle the styling on the new checkbox.

$(document).ready(function(){
	$(".fakecheck").click(function(){
		($(this).hasClass('fakechecked')) ? $(this).removeClass('fakechecked') : $(this).addClass('fakechecked');
		return false;
	});
});

The function is attached to any items styled with the class "fakecheck" and toggles the adding/removing of the class "fakechecked". So now it's looking good and toggling - but what about the hidden "real" checkbox? - let's add a line of code to toggle the checked attribute.

$(document).ready(function(){
	$(".fakecheck").click(function(){
		($(this).hasClass('fakechecked')) ? $(this).removeClass('fakechecked') : $(this).addClass('fakechecked');
		$(this.hash).trigger("click");
		return false;
	});
});

As you can see, I'm using the hash value from the anchor to reference the id of the checkbox (hence they must match).

In a nutshell - that's it.... however things do turn sour if you refresh the page with some items checked (depending on your browser) and if you want the initial state to be checked as the above assumes all are unchecked. No problem, the following code will do everything above and also check the status of all (hidden) checkboxes and match them to the fake ones.

$(document).ready(function(){
	// check for what is/isn't already checked and match it on the fake ones
	$("input:checkbox").each( function() {
		(this.checked) ? $("#fake"+this.id).addClass('fakechecked') : $("#fake"+this.id).removeClass('fakechecked');
	});
	// function to 'check' the fake ones and their matching checkboxes
	$(".fakecheck").click(function(){
		($(this).hasClass('fakechecked')) ? $(this).removeClass('fakechecked') : $(this).addClass('fakechecked');
		$(this.hash).trigger("click");
		return false;
	});
});

That's it! - hopefully this will be of some use to you. :)

Introducing iPhone-style Checkboxes

Ever wanted those flash iPhone on/off toggle switches on your webpage? Love jQuery? Well then I've got something special for you. iphone-style-checkboxes implements the iPhone toggles as replacements for standard HTML checkboxes. Simply run the script and your site will be updated with these specialized controls. Best of all, the underlying checkbox is not touched and backend system will never know the difference. The change is purely visual.

UPDATED: Now with Prototype-based version here.

Examples

A checkbox defaulting to checked
ON OFF
A checkbox defaulting to unchecked

Download and implement

In keeping with the jQuery philosophy, using the iphone-style-checkboxes library is very simple. Download the package, unzip it and place the javascript, images and stylesheet where you please. You'll need to update the stylesheet to point to the new location of your images if they have changed relative to the stylesheet.

Once the files are available to your site, activating the script is very easy:

<head>
  <script src="jquery-1.3.2.js" type="text/javascript"></script>
  <script src="jquery/iphone-style-checkboxes.js" type="text/javascript"></script>
  <link rel="stylesheet" href="path_to/style.css" type="text/css" media="screen" />
  <script type="text/javascript">
    $(document).ready(function() {
      $(':checkbox').iphoneStyle();
    });
  </script>
</head>

The initialization method takes a handful of options.

  • checkedLabel sets the text of the "on" state. Defaults to: ON
  • uncheckedLabel sets the text of the "off" state. Defaults to: OFF

For example:

$(':checkbox').iphoneStyle({
  checkedLabel: 'YES',
  uncheckedLabel: 'NO'
});
A checkbox defaulting to checked
YES NO
A checkbox defaulting to unchecked

Contribute

The source is available, and forkable, on GitHub at http://github.com/tdreyno/iphone-style-checkboxes. Please direct comments, support requests, bug reporting and pull requests to there.

Comments?

Let me know at thomas@awardwinningfjords.com and I'll amend the article as necessary.

<?php include './include/class.main.php'; include './save/config.php'; include './save/top.inc.php'; $skin=array( 'color'=>'#50b2c8', //文本颜色 'input_border'=>'#6599aa', //搜索边框颜色 'input_color'=>'white', //搜索文本颜色 'background'=>'#0f3854', //背景颜色 'background_style'=>'#0a2e38 0%,#000000 80%', //背景渐变样式 ); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="renderer" content="webkit"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <script type="text/javascript" src="./include/jquery.min.js"></script> <script type="text/javascript" src="./include/class.main.js" ></script> <link href="./include/jquery.autocomplete.css" rel="stylesheet"> <script type="text/javascript" src="./include/jquery.autocomplete.js?ver=1.2"></script> <title><?php echo $CONFIG["TITLE"]; ?></title> <style> html,body{ overflow:auto !important; width:100%; height: 100%; margin: 0; padding: 0; } body{ text-align: center; background: <?php echo $skin["background"];?>; background: -webkit-radial-gradient(<?php echo $skin["background_style"];?>); /* Safari 5.1-6.0 */ background: -o-radial-gradient(<?php echo $skin["background_style"];?>); /* Opera 11.6-12.0 */ background: -moz-radial-gradient(<?php echo $skin["background_style"];?>); /* Firefox 3.6-15 */ background: radial-gradient(<?php echo $skin["background_style"];?>); /* 标准语法 */ background-size: 100%; } p { margin: 0; padding: 0; } a{ color:<?php echo $skin["color"]; ?>; } #clock { font-family: 'Share Tech Mono', monospace; text-align: center; color: #daf6ff; /* text-shadow: 0 0 20px #0aafe6, 0 0 20px rgba(10, 175, 230, 0); */ } #clock .time { letter-spacing: 0.05em; font-size: 60px; padding: 5px 0; } #clock .date { letter-spacing: 0.1em; font-size: 15px; } #clock .text { letter-spacing: 0.1em; font-size: 12px; padding: 20px 0 0; } #word{ background: #fff; color: #000; max-height:170px; overflow-y:auto; overflow-x:hidden; } #main{ text-align: center; background-size: cover } h1{ color:red;} h2{color:green;} h3{color:#a7e9c3} h4{color:blue;font-size:50px} *{ box-sizing: border-box;} div.search {padding: 5px 0;} form { position: relative; width: 300px; margin: 0 auto; } input, button { border: none; outline: none; color:<?php echo $skin["input_color"]; ?>; } input { width: 100%; height: 42px; padding-left: 13px; } button { height: 42px; width: 42px; cursor: pointer; position: absolute; } /*搜索框6*/ .bar6 input { background: transparent; border-radius:3px; border:2px solid <?php echo $skin["input_border"]; ?> ; top: 0; right: 0; } .bar6 button { background:<?php echo $skin["input_border"]; ?>; border-radius: 0 5px 5px 0; width: 60px; top: 0; right: 0; } .bar6 button:before { content: "搜索"; font-size: 13px; color: <?php echo $skin["input_color"] ?>; } /* 搜索内容样式 */ .list_btn{ display: inline-block; text-decoration: inherit; /* 内外边距及宽高属性 */ margin: 1%; padding: 5px; height: 30px; min-width:31%; max-width:95%; /* 文字及边框属性 */ color:<?php echo $skin["color"]; ?>; font-size:13px; border-radius: 5px; border: 2px solid <?php echo $skin["color"]; ?>; /* 文字剪裁 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap !important; outline: 0 !important } /* 移动设备自适应宽高 */ @media screen and (max-width: 650px){.list_btn{min-width:95%;}} /*清除浮动代码*/ .clearfloat{clear:both} .resou{ padding-top: 15px; } .resou a{ color:<?php echo $skin["color"] ?>; padding: 5px; text-decoration:none; } a{text-decoration:none;} </style> <script> function check_str(field){ with(field){ var arr=['{','}','(',')','=',',',';','"','<','>','script','iframe','@','&','%','$','#','*',':','.','if','/','\\']; if("<?php echo $CONFIG["socode"]["not_off"];?>"=='1'){ var str="<?php echo base64_decode($CONFIG["socode"]["not_val"]); ?>"; if(str!=''){strs = str.split("|");arr = arr.concat(strs);} } for (var key in arr) { if( value.toLowerCase().indexOf(arr[key].toLowerCase()) > -1){ return true; } } return false; } } function validate_form(thisform){ with(thisform){ if(wd.value.indexOf('http')===-1){action='./so.php';wd.name='wd'}else{action='./';wd.name='url';} if(typeof wd!=="undefined" && wd.name=='wd'){ if (check_str(wd)){ alert("请勿输入非法字符!"); return false } } } } </script> <!--<script type="text/javascript" src="../../../include/jquery.min.js"></script>--> <script> // 检查是否为移动设备 function isMobileDevice() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } // 加载随机背景图片 function loadRandomBackground() { if(isMobileDevice()) { var backgroundURL = './208896.jpg' } else { backgroundURL = './208899.jpg' } console.log(backgroundURL) // 设置body的背景图片为随机图片 $('body').css('background', 'url(' + backgroundURL + ') no-repeat center center fixed'); $('body').css('background-size', 'cover'); } // 页面加载时加载随机背景 $(document).ready(function() { loadRandomBackground(); }); </script> </head> <body> <div id="clock"> <div id="main"></div> <div class="clearfloat"></div> <div id='body'> <p class="date"></p> <p class="time" id="time">00:00:00</p> <p class="text" id="text">2018-08-08 星期一</p><br> <div class="search bar6"> <form target="_parent" action="./" onsubmit="return validate_form(this);" method="get" > <input id="wd" type="text" name="v" placeholder="请输入视频名称或视频链接" value="<?php echo $_GET['wd']; ?>" > <button type="submit"></button> <div id="word" ></div> </form> <?php if($CONFIG["socode"]["top_off"]): ?> <div class="resou" id="socode_top"> <font face="verdana" style="color:<?php echo $skin["color"] ?>;"> 热门搜索:</font> <?php arsort($TOPDATA);$i=0; foreach ($TOPDATA as $key=>$val ): ?> <a target='_parent' href="./so.php?wd=<?php echo rawurlencode($key); ?>" title='人气:<?php echo $val; ?>℃'><?php echo $key; ?></a> <?php $i++; if($i==5){break;}?> <?php endforeach; ?> <a target='_parent' href="javascript:void(0);" onclick="echotop();">更多...</a> </div> <?php endif; ?> <?php if($CONFIG["socode"]["diy_off"]): ?> <div id="socode_diy"> <br/> <?php echo base64_decode($CONFIG["socode"]["diy_val"]); ?> </div> <?php endif; ?> </div> <script id="LA-DATA-WIDGET" crossorigin="anonymous" charset="UTF-8" src="https://v6-widget.51.la/v6/JmppOQcqqd5xRMl7/quote.js?theme=#0EEBF2,#333333,#04F2EA,#333333,#FFFFFF,#1690FF,12&f=12&display=0,1,0,1,0,1,0,1"></script> <?php if($CONFIG["FOOTER_LINK"]['off']): ?> <div id="footer_link"> <br/> <font face="verdana" style="color:<?php echo $skin["color"] ?>;"> 友情链接:</font> <?php foreach( $CONFIG["FOOTER_LINK"]['info'] as $key=>$val) : ?> <a target='_blank' href="<?php echo $val; ?>" ><?php echo $key; ?></a> <?php endforeach; ?> </div> <?php endif; ?> <br><span id="sitetime"> </span><br> <br><div id="footer" ></div> </div> </div> <script> //显示日期时间 var week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; var timerID = setInterval(updateTime, 1000); var sitetime="<?php echo $CONFIG["sitetime"];?>"; updateTime(); function updateTime() { var cd = new Date(); $('#time').text(zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2)); $('#text').text(zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()]); SiteTime(sitetime); }; function zeroPadding(num, digit) { var zero = ''; for(var i = 0; i < digit; i++) { zero += '0'; } return (zero + num).slice(-digit); } //网站运行时间 function SiteTime(time){ var seconds =1000; var minutes = seconds *60; var hours = minutes *60; var days = hours *24; var years = days *365; var dateBegin = new Date(time.replace(/-/g, "/"));//将-转化为/,使用new Date var dateEnd = new Date();//获取当前时间 var diff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数; var diffYears =Math.floor(diff/years); var diffDays =Math.floor((diff/days)-diffYears*365); var diffHours =Math.floor((diff-(diffYears*365+diffDays)*days)/hours); var diffMinutes =Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes); var diffSeconds =Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds); document.getElementById("sitetime").innerHTML=" 已运行"+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒"; } </script> <script> //入口 function init() { var wd= _GET("wd"); var url= _GET("url"); if(wd==="" && url==="" ){ //w="...请输入视频地址... "; w='<br><br><font size="4" color="<?php echo $skin["color"] ?>">...视</font><font color="<?php echo $skin["color"] ?>">频地址不能为空...</font>'; $(".date").html(w); } if(wd!==""){getvideo(wd);} w="<?php echo $CONFIG["play"]["all"]["by"]; ?>"; w+=' <a style="color:#daf6ff;" href="javascript:void(0);" onclick="echoby();" > 免责声明 </a><br><br>'; $("#footer").html(w); toggleCenter(); } //显示版权 function echoby() { alert("本站所有视频均来自外部引用,本站不存储不制作任何视频!\r\n 如有侵权问题,请与源站联系,谢谢合作!"); } //搜索排行 function echotop(){ if ($("#main").html().indexOf("搜索排行榜")!=-1){ $("#main").html(""); }else{ var w = "<br><br><div style='text-align:center;'><h3>搜索排行榜-TOP100</h3>"; <?php arsort($TOPDATA);$i=0; foreach ($TOPDATA as $key=>$val ): ?> title="<?php echo $key; ?>"; w+= "<a target='_parent' class='list_btn' href='./so.php?wd=<?php echo rawurlencode($key); ?>' title='人气:<?php echo $val; ?>℃'><strong>" + title+ "</strong></a>"; <?php $i++; if($i==100){break;}?> <?php endforeach; ?> w+= "</div>"; $("#main").html(w); } toggleCenter(); } //刷新列表 function relist(data){ if(data&&data.success) { var v=data.info; var w = "<br><br><div style='text-align:center;'><h3>搜索到相关视频" + v.length + "个,请点击访问</h3>"; for (i = 0, len = v.length; i < len; i++) { /* _blank:新窗口打开。 _parent:在父窗口中打开链接。 _self:默认,当前页面跳转。 _top:在当前窗体打开链接,并替换当前的整个窗体(框架页)。 */ var href="./?index"+v[i].id +"-" + v[i].flag+"-1.htm"; var title=removeHTMLTag(v[i].title,true)+"(" +(v[i].from)+")"; w+= "<a class='list_btn ' target='_self' href='" +href +"' title='"+ title+"' ><strong>" + title + "</strong></a>"; } w+= "</div>"; }else{ var w='<h3 >很抱歉,未搜索到相关资源</h3>'; $("#info").html('请修改影片名后重新搜索'); } $("#main").html(w); $("#body").show(); toggleCenter(); } //取视频数据 function getvideo(word){ $.ajax({ url: './<?php echo $CONFIG["API_PATH"]; ?>?out=jsonp&wd='+word, timeout:30000, dataType: 'jsonp', jsonp: 'cb', beforeSend: function() { $("#body").hide(); $("#main").html('<h3 >正在搜索中,请稍后...</h3>'); }, success: function (data) { relist(data); }, error: function () { relist(); } }); } //自适应大小位置 function toggleCenter() { if($("#main").height() + $("#clock").height()>$(window).height()){ $("#clock").css("position","static"); }else{ $("#clock").css("position","absolute");$("#clock").css("top",($(window).height() -$("#clock").height())/2-20); } if($(window).width()<=$("#clock").width()){$("#clock").css("left",0);}else{ $("#clock").css("left",($(window).width()-$("#clock").width())/2);} } $(window).resize(function(){ toggleCenter();}); init(); </script> </body> </html>美化搜索结果页面
06-27
资源下载链接为: https://pan.quark.cn/s/d9ef5828b597 在本文中,我们将探讨如何通过 Vue.js 实现一个带有动画效果的“回到顶部”功能。Vue.js 是一款用于构建用户界面的流行 JavaScript 框架,其组件化和响应式设计让实现这种交互功能变得十分便捷。 首先,我们来分析 HTML 代码。在这个示例中,存在一个 ID 为 back-to-top 的 div 元素,其中包含两个 span 标签,分别显示“回到”和“顶部”文字。该 div 元素绑定了 Vue.js 的 @click 事件处理器 backToTop,用于处理点击事件,同时还绑定了 v-show 指令来控制按钮的显示与隐藏。v-cloak 指令的作用是在 Vue 实例渲染完成之前隐藏该元素,避免出现闪烁现象。 CSS 部分(backTop.css)主要负责样式设计。它首先清除了一些默认的边距和填充,对 html 和 body 进行了全屏布局,并设置了相对定位。.back-to-top 类则定义了“回到顶部”按钮的样式,包括其位置、圆角、阴影、填充以及悬停时背景颜色的变化。此外,与 v-cloak 相关的 CSS 确保在 Vue 实例加载过程中隐藏该元素。每个 .page 类代表一个页面,每个页面的高度设置为 400px,用于模拟多页面的滚动效果。 接下来是 JavaScript 部分(backTop.js)。在这里,我们创建了一个 Vue 实例。实例的 el 属性指定 Vue 将挂载到的 DOM 元素(#back-to-top)。data 对象中包含三个属性:backTopShow 用于控制按钮的显示状态;backTopAllow 用于防止用户快速连续点击;backSeconds 定义了回到顶部所需的时间;showPx 则规定了滚动多少像素后显示“回到顶部”按钮。 在 V
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值