- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title></title>
- <script src1="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
- <style>
- .layouttb {
- }
- .layouttb .layoutfocus{
- background-color:#ff9933
- }
- .layouttb td{
- width:50px;
- height:20px;
- cursor:pointer;
- background-color: gray;
- }
- .layouttb .layoutselect{
- background-color: #0099cc;
- }
- </style>
- </head>
- <body>
- <input type="text" value="middle" id="txtText" />
- </body>
- </html>
- <script>
- /**
- *
- * author:奥博杰克特
- */
- $(function() {
- $.fn.layoutselect = function(options) {
- var opts = $.extend({}, $.fn.layoutselect.defaults, options);
- return this.each(function() {
- var input = $(this);
- var html = '<table class="layouttb"><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>';
- input.after(html);
- var table = input.next();
- var onSetValue = function() {
- var tmpv = input.val();
- if (tmpv) {
- var sdata = opts.selectData;
- var nowindex = -1;
- for (var i = 0; i < 9; i++) {
- if (sdata[i] === tmpv) {
- nowindex = i;
- break;
- }
- }
- $('.layoutselect', table).removeClass('layoutselect');
- if (nowindex >= 0) {
- var row = Math.floor(nowindex / 3), col = nowindex % 3;
- table.find('tr:eq(' + row + ')').children('td:eq(' + col + ')').addClass('layoutselect');
- }
- }
- };
- input.change(onSetValue);
- onSetValue();
- $('td', table).hover(function() {
- var td = $(this);
- if (td.hasClass('layoutselect')) {
- } else {
- td.addClass('layoutfocus');
- }
- }, function() {
- var td = $(this);
- td.removeClass('layoutfocus');
- }).click(function() {
- var td = $(this);
- $('.layouttb .layoutselect').removeClass('layoutselect');
- td.addClass('layoutselect').removeClass('layoutfocus');
- var col = td.parent().find("td").index(td);
- var tr = td.parent();
- var row = tr.parent().find('tr').index(tr);
- var index = row * 3 + col;
- var value = opts.selectData[index];
- input.val(value);
- });
- });
- };
- $.fn.layoutselect.defaults = {
- selectData: ['lefttop', 'middletop', 'righttop',
- 'leftmiddle', 'middle', 'rightmiddle',
- 'leftbottom', 'middlebottom', 'rightbottom']//九宫格对应值
- };
- });
- </script>
- <script>
- $(function() {
- //使用方法
- $('#txtText').layoutselect();
- });
- </script>
- //该片段来自于http://www.codesnippet.cn/detail/0601201511499.html
来源: http://www.codesnippet.cn/detail/0601201511499.html