русс | укр

Языки программирования

ПаскальСиАссемблерJavaMatlabPhpHtmlJavaScriptCSSC#DelphiТурбо Пролог

Компьютерные сетиСистемное программное обеспечениеИнформационные технологииПрограммирование

Все о программировании


Linux Unix Алгоритмические языки Аналоговые и гибридные вычислительные устройства Архитектура микроконтроллеров Введение в разработку распределенных информационных систем Введение в численные методы Дискретная математика Информационное обслуживание пользователей Информация и моделирование в управлении производством Компьютерная графика Математическое и компьютерное моделирование Моделирование Нейрокомпьютеры Проектирование программ диагностики компьютерных систем и сетей Проектирование системных программ Системы счисления Теория статистики Теория оптимизации Уроки AutoCAD 3D Уроки базы данных Access Уроки Orcad Цифровые автоматы Шпаргалки по компьютеру Шпаргалки по программированию Экспертные системы Элементы теории информации

Click()


Дата добавления: 2015-07-09; просмотров: 574; Нарушение авторских прав


Description: Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

_____________________________________________________________________________________

Шашки

 

Script.js
function setUpPieces() {

//select all the divs with class 'piece'

//add the 'light' class to half of them

//add the 'dark' to the other half

$('div.piece:even').addClass("dark");

$('div.piece:odd').addClass("light");

}

 

function movePieceTo($piece,newTop,newLeft) {

//set the css 'top' and 'left'

//attributes of the passed piece

//to the arguments newTop and newLeft

$piece.css('top', newTop);

$piece.css('left', newLeft);

}

 

function setUpBoard() {

//iterate through all of the divs

//with class `square`

//figure out whether each one should be

//light or dark, and assign the proper class

$('div.square').each(function(index,square){

$square = $(square);

if (!lightOrDark(index)){

$square.addClass('light');

}else {

$square.addClass('dark');

}

});

 

//heres a helper function that takes a number between

//0 and 63 (inclusive) and returns 1 if the square should be

//dark, and 0 if the square should be light

function lightOrDark(index) {

var x = index % 8;

var y = Math.floor(index / 8);

var oddX = x % 2;

var oddY = y % 2;

return (oddX ^ oddY);

}

 

}

 

function toggleSelect($piece) {

//if $piece has the class 'selected',

//remove it

if( $piece.hasClass('selected') ) {

$piece.removeClass('selected');

}

//if $piece does not have the class 'selected'

//make sure no other divs with the class 'piece'

//have that class, then set $piece to have the class

else {

$('div.piece').removeClass('selected');



$piece.addClass('selected');

}

}

 

 

function incrementMoveCount() {

moveCount = parseInt($('span#moveCount').html(),10);

moveCount++;

$('span#moveCount').html(moveCount);

}

Checkers.html
<html>

 

<head>

 

<title>Checkers</title>

 

<link rel="stylesheet" href="style.css"/>

 

<script src='script.js'></script>

 

<script src='provided.js'></script>

 

 

</head>

 

<body>

 

<div id="game">

<div id="board">

</div>

 

<div id="pieces">

</div>

 

</div>

 

<div id="meta">

<h1>Checkers</h1>

<h4>Moves: <span id="moveCount">0</span></h4>

</div>

 

</body>

 

</html>

Style.css

div#game {

position:relative;

}

 

 

div#board {

 

float:left;

 

 

height:382px;

width:382px;

 

border-style:solid;

border-width:9px;

border-color:#DEB887;

}

 

div.square {

 

float:left;

 

position:relative;

 

width:46px;

height:46px;

border-width:2px;

 

 

border-right-style:solid;

border-bottom-style:solid;

 

border-color:#444;

}

 

div.square.movable:hover {

 

-webkit-box-shadow: inset 0px 0px 8px #FFD700;

-moz-box-shadow: inset 0px 0px 8px #FFD700;

box-shadow: inset 0px 0px 8px #FFD700;

cursor:pointer;

}

 

/* the bottom row */

div.square:nth-last-child(-n + 8) {

border-bottom-style:none;

}

 

/* the sides */

div.square:nth-child(8n) {

border-right-style:none;

}

 

div.square.light {

background-color:#ccc;

}

 

div.square.dark {

background-color:#333;

}

 

div#pieces {

position:absolute;

/* 9 px puts us inside of the board's borders;*/

left:9px;

top:9px;

background-color:green;

}

 

div.piece {

position:absolute;

width:32px;

height:32px;

margin:7px;

 

-webkit-box-shadow: 0px 0px 3px #666;

-moz-box-shadow: 0px 0px 3px #666;

box-shadow: 0px 0px 3px #666;

 

-webkit-border-radius:16px;

-moz-border-radius:16px;

border-radius:16px;

 

background-color:blue;

 

}

 

div.piece:hover {

-webkit-box-shadow: 0px 0px 8px #FFD700;

-moz-box-shadow: 0px 0px 8px #FFD700;

box-shadow: 0px 0px 8px #FFD700;

cursor:pointer;

}

 

div.piece.selected {

-webkit-box-shadow: 0px 0px 8px #FFD700;

-moz-box-shadow: 0px 0px 8px #FFD700;

box-shadow: 0px 0px 8px #FFD700;

}

 

div.piece.light {

background-color:red;

}

 

div.piece.dark {

background-color:blue;

}

 

div#meta {

float:right;

}

Provided.js

//global variables for one square

var width = 46;

var border = 2;

 

//utility function for translating an x,y coordinate

//to a pixel position

//the convention is that the square in the upper left

//corner is at position 0,0

//the square in the upper right, at 7,0 and the lower

//right at 7,7

function getPixels(x,y) {

//ok... so takes an x,y position, returns

//pixels from the left, right

 

return {

'top': (y * (width+border))+'px',

'left': (x * (width+border))+'px'

};

}

 

//utility function for turning a pixel position

//into the x,y coordinate of a square on the board

//it follows the same coordinate convention as getPixels

function getCoords(top,left) {

//returns an x and a y

//given a top and left pixels

return {

'x': left / (width + border),

'y': top / (width + border)

};

}

 

//utility function for returning

//the set of unoccupied dark squares

//(possible places to move a checker piece)

function getMovableSquares() {

 

//select all of the squares

var $squares = $('div.square');

 

//select the occupied ones using the jQuery map() method

//map creates a new object from an existing one

//using a translation function

var $takenSquares =

$('div.piece').map(function(index,piece) {

 

//this function translates a piece

var position = $(piece).position();

var coords = getCoords(position.top,position.left);

var squareIndex = coords.y * 8 + coords.x;

return $squares[squareIndex];

});

 

var $out = $('div.square.dark').not($takenSquares);

return $out;

}

 

$('document').ready(function() {

 

//Creating the 64 squares and adding them to the DOM

var squareCount = 8*8;

for (var i = 0;i<squareCount;i++) {

 

//this line creates a new div with the class 'square'

//and appends it to the div with id 'board'

$('div#board').append($('<div/>').addClass('square'));

}

 

//YOUR CODE

//set up the board with the correct classes

//for the light and dark squares

setUpBoard();

 

 

//creating the 24 pieces and adding them to the DOM

var pieceCount = 24;

for (var i=0;i<pieceCount;i++) {

 

//this line appends an empty div

//with the class 'piece' to the div with id 'pieces'

$('div#pieces').append($('<div/>').addClass('piece'));

 

}

 

//YOUR CODE

//sets up the classes for the different types of piece

setUpPieces();

 

//this loop moves all the light pieces to their initial positions

$('div.piece.light').each(function(index,piece) {

 

//turning the index (from 0 - 11)

//into a x,y square coordinate using math

var y = Math.floor(index / 4);

var x = (index % 4) * 2 + (1 - y%2);

 

//turning the x,y coordingate into a pixel position

var pixelPosition = getPixels(x,y);

 

//YOUR CODE

//actually moving the piece to its initial position

movePieceTo($(piece),pixelPosition.top,pixelPosition.left);

});

 

//this loop moves all the dark pieces to their initial positions

$('div.piece.dark').each(function(index,piece) {

 

//turning the index (from 0 - 11)

//into a x,y square coordinate using math

var y = Math.floor(index/4) + 5;

var x = (index % 4) * 2 + (1-y%2);

 

//turning the x,y coordinate into a pixel position

var pixelPosition = getPixels(x,y);

 

//YOUR CODE

//moving the piece to its initial position

movePieceTo($(piece),pixelPosition.top,pixelPosition.left);

});

 

//set up initial squares

//the class 'movable' represents a square

//that is unoccupied

getMovableSquares().addClass('movable');

 

//and now the events

$('div.piece').click(function() {

 

//turn `this` into a jQuery object

var $this = $(this);

 

//YOUR CODE

//toggleing the 'selected' class of this piece

//and possible deselecting other pieces

toggleSelect($this);

});

 

$('div.square').click(function() {

 

//turn `this` into a jQuery object

var $this = $(this);

 

//if $this is a legal square to move to...

if ($this.hasClass('movable')) {

 

//get the piece with the class 'selected'

var $selectedPiece = $('div.piece.selected');

 

//we only move if there is exactly one selected piece

if ($selectedPiece.length == 1) {

//get the index of the square

//and translate it to pixel position

var index = $this.prevAll().length;

var x = index % 8;

var y = Math.floor(index / 8);

var pixels = getPixels(x,y);

 

//YOUR CODE

//actually do the moving

movePieceTo($selectedPiece,pixels.top,pixels.left);

 

//YOUR CODE

//increment the move counter

incrementMoveCount();

 

//un-select the piece

$selectedPiece.removeClass('selected');

 

//set the new legal moves

$('div.square').removeClass('movable');

getMovableSquares().addClass('movable');

}

 

}

});

});

 

_____________________________________________________________________________________

$ и $()

var jQuery = $; - функция, возвращает объект.

var jQueryObject = $(); - объект

$ methods and attributes

  • fn
  • extend
  • noConflict
  • isReady
  • readyWait
  • holdReady
  • ready
  • bindReady
  • isFunction
  • isArray
  • isWindow
  • isNumeric
  • type
  • isPlainObject
  • isEmptyObject
  • error
  • parseJSON
  • parseXML
  • noop
  • globalEval
  • camelCase
  • nodeName
  • each
  • trim
  • makeArray
  • inArray
  • merge
  • grep
  • map
  • guid
  • proxy
  • access
  • now
  • uaMatch
  • sub
  • browser
  • Callbacks
  • Deferred
  • when
  • support
  • cache
  • uuid
  • expando
  • noData
  • hasData
  • data
  • removeData
  • _data
  • acceptData
  • _mark
  • _unmark
  • queue
  • dequeue
  • valHooks
  • attrFn
  • attr
  • removeAttr
  • attrHooks
  • propFix
  • prop
  • propHooks
  • event
  • removeEvent
  • Event
  • find
  • expr
  • unique
  • text
  • isXMLDoc
  • contains
  • filter
  • dir
  • nth
  • sibling
  • buildFragment
  • fragments
  • clone
  • clean
  • cleanData
  • cssHooks
  • cssNumber
  • cssProps
  • style
  • css
  • swap
  • curCSS
  • get
  • post
  • getScript
  • getJSON
  • ajaxSetup
  • ajaxSettings
  • ajaxPrefilter
  • ajaxTransport
  • ajax
  • param
  • active
  • lastModified
  • etag
  • speed
  • easing
  • timers
  • fx
  • offset
  • boxModel
  • boxModel

$() methods and attributes

  • constructor
  • init
  • selector
  • jquery
  • length
  • size
  • toArray
  • get
  • pushStack
  • each
  • ready
  • eq
  • first
  • last
  • slice
  • map
  • end
  • push
  • sort
  • splice
  • extend
  • data
  • removeData
  • queue
  • dequeue
  • delay
  • clearQueue
  • promise
  • attr
  • removeAttr
  • prop
  • removeProp
  • addClass
  • removeClass
  • toggleClass
  • hasClass
  • val
  • on
  • one
  • off
  • bind
  • unbind
  • live
  • die
  • delegate
  • undelegate
  • trigger
  • triggerHandler
  • toggle
  • hover
  • blur
  • focus
  • focusin
  • focusout
  • load
  • resize
  • scroll
  • unload
  • click
  • dblclick
  • mousedown
  • mouseup
  • mousemove
  • mouseover
  • mouseout
  • mouseenter
  • mouseleave
  • change
  • select
  • submit
  • keydown
  • keypress
  • keyup
  • error
  • contextmenu
  • find
  • has
  • not
  • filter
  • is
  • closest
  • index
  • add
  • andSelf
  • parent
  • parents
  • parentsUntil
  • next
  • prev
  • nextAll
  • prevAll
  • nextUntil
  • prevUntil
  • siblings
  • children
  • contents
  • text
  • wrapAll
  • wrapInner
  • wrap
  • unwrap
  • append
  • prepend
  • before
  • after
  • remove
  • empty
  • clone
  • html
  • replaceWith
  • detach
  • domManip
  • appendTo
  • prependTo
  • insertBefore
  • insertAfter
  • replaceAll
  • css
  • serialize
  • serializeArray
  • ajaxStart
  • ajaxStop
  • ajaxComplete
  • ajaxError
  • ajaxSuccess
  • ajaxSend
  • show
  • hide
  • _toggle
  • fadeTo
  • animate
  • stop
  • slideDown
  • slideUp
  • slideToggle
  • fadeIn
  • fadeOut
  • fadeToggle
  • offset
  • position
  • offsetParent
  • scrollLeft
  • scrollTop
  • innerHeight
  • outerHeight
  • height
  • innerWidth
  • outerWidth
  • width

_____________________________________________________________________________________

$.isArray

$.isArray() is a method that will return true if the object passed to it is an array, and false otherwise. It is very useful because the pure JavaScript typeof keyword will return the same value for both arrays and objects.

function safeLength(object) {

if ($.isArray(object)){

return object.length;

}

else {

return 0;

}

}

_____________________________________________________________________________________

Map()

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

The .map() method is particularly useful for getting or setting the value of a collection of elements.

function alertTheEachMes() {

 

//use $() to select all the divs with class 'eachMe'

var $allOfTheEachMeDivs = $('div.eachMe');

 

//keeper for our alerts

var capturedAlerts = $.map($allOfTheEachMeDivs,function(value)

{

return $(value).html();

});

return capturedAlerts;

}

_____________________________________________________________________________________



<== предыдущая лекция | следующая лекция ==>
 | Data( key, value )


Карта сайта Карта сайта укр


Уроки php mysql Программирование

Онлайн система счисления Калькулятор онлайн обычный Инженерный калькулятор онлайн Замена русских букв на английские для вебмастеров Замена русских букв на английские

Аппаратное и программное обеспечение Графика и компьютерная сфера Интегрированная геоинформационная система Интернет Компьютер Комплектующие компьютера Лекции Методы и средства измерений неэлектрических величин Обслуживание компьютерных и периферийных устройств Операционные системы Параллельное программирование Проектирование электронных средств Периферийные устройства Полезные ресурсы для программистов Программы для программистов Статьи для программистов Cтруктура и организация данных


 


Не нашли то, что искали? Google вам в помощь!

 
 

© life-prog.ru При использовании материалов прямая ссылка на сайт обязательна.

Генерация страницы за: 0.044 сек.