js」カテゴリーアーカイブ

テーブルセルをhoverして色を付ける時のテクニック

テーブルセルをhoverして色を付ける時のテクニックとして、

td:hover {
  background-color: #ff0000;
}

とかあると思うのですが、rowspanとかで結合してるときに使える時があるのがこれです。
使えない時もあるかもしれませんが、こういう風にやりたいときに有効です。

<table>
  <tbody>
    <tr>
      <td rowspan="3">Alphabet</td>
      <td rowspan="2">a</td>
      <td>b</td>
      <td>c</td>
    </tr>
    <tr>
      <td>d</td>
      <td>e</td>
    </tr>
    <tr>
      <td>f</td>
      <td>g</td>
      <td>h</td>
    </tr>
    <tr>
      <td rowspan="3">Number</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
      <td>8</td>
      <td>9</td>
    </tr>
  </tbody>
</table>
$("td").hover(function() { $el = $(this); $el.parent().addClass("hover");if ($el.parent().has('td[rowspan]').length == 0) $el .parent() .prevAll('tr:has(td[rowspan]):first') .find('td[rowspan]') .addClass("hover"); }, function() { $el .parent() .removeClass("hover") .prevAll('tr:has(td[rowspan]):first') .find('td[rowspan]') .removeClass("hover"); });
.hover { background: red; }

印刷時のみ有効になるJS

以前書いた印刷時にのみ有効になるスタイルに関連して、印刷時のみ有効になるJSです。
要するに、ブラウザで「印刷ボタン」を押した時に表示されるプレビューを制御します。

印刷する時に不要な要素を削除したり・・って言うのは、cssの@media print でなんとかなりますが、セル結合の制御まではcssでは出来ないのでこれはかなり有効です。

$(window).on('beforeprint', function(event) {

//処理
$("hoge").attr("colSpan","1")//これは印刷時のみ横セル結合を1にする


});

以下は、印刷キャンセルを押した後や印刷を終えた後の処理

$(window).on('afterprint', function(event) {

//処理
$("hoge").attr("colSpan","2")//横セル結合を2にする(戻す)

});

単純にヘッダーの高さを計算してcontentsにmargin-topつける方法

こんな感じです。jQuery3以上を使っている場合は、functionで囲う必要はありません。

$(window).on('load resize', function() {

var h = $('#header').height();

$( '#contents' )
.css({
'margin-top' : h + 'px',
})

});

下部固定バナーをスクロール時非表示で話すとフワっと出す

これでクラス名指定してあげればすぐです。
ちなみに、下部固定バナーをサイトのフッターの上で止めたいやつ と併用すると良きですね。

jQuery(document).ready(function(){
var bnrElm = jQuery(".sticky_footer"); // バナー要素

jQuery(window).on("scroll touchmove", function(e){ //スクロール中に判断する
bnrElm.stop(); //アニメーションしている場合、アニメーションを強制停止
bnrElm.css('display', 'none').delay(500).fadeIn('fast'); //スクロール中は非表示にして、500ミリ秒遅らせて再び表示
});
});

下部固定してる要素がフッターまで来たらフッターの上で止めるJS

スマホサイトとかで流行りのフッター固定バナー的なやつがスクロールしてるうちにフッターにぶち当たったときの処理。
display:flex;状態だとフッターの上に被っちゃうので、被らないようにします。

まずHTML。ちなみにソースの中の「height」は適宜変えてください。
あと、フッターの上で固定させたい要素は、固定させたい場所に書いてください。(position指定無し状態での単純な位置)
↓だとちゃんとfooterの上に書いて、positionとか指定しない場合ちゃんとfooterの上にぴちっと出ると思います。

それと、headerとかcontentとかの構成は適当です。何が大事かって、固定したい要素の#sticky_footerの器をしっかり作るのが大事なのです。
何故なのかは後述します。

<header>
ヘッダ~
</header>

<div id="content">
こんてんつ!
</div>

<div style="height:50px;width:100%;">
<footer id="sticky_footer">

#sticky_footerを固定したい!

</footer>
</div>

<footer id="main_footer">
フッタ~
</footer>

CSSです。ここでどういう要素か定義しておきます。主に装飾。

footer.sticky_footer{
background-color: #ff00ff;
height:50px;
width: 100%;
color:#fff;
text-align: center;
line-height: 50px;
}

JSです。クラス名とかは適宜変えてください。

jQuery(window).on("scroll", function() {
documentHeight = jQuery(document).height();
scrollPosition = jQuery(this).height() + jQuery(this).scrollTop();
footerHeight = jQuery("#site_footer").outerHeight();

if (documentHeight - scrollPosition <= footerHeight) {
jQuery("#sticky_footer").css({
position: "static",
bottom: "auto"
});
} else {
jQuery("#sticky_footer").css({
position: "fixed",
bottom: 0
});
}
});

こんな感じです。

あと上で言ってたことですが、ちゃんと固定したい要素と同じ高さの器を作っておかないと、いざ要素が固定された時に新要素が入ってきた!となってサイトの高さが変わってスクロールバーがグニュっと動いてフッターがガクッと落ちた感じになっちゃいますね。そういうための対策です。
これはあまり他のサイトも書いてなくて困りました。

要素をふわっとスクロールjQueryの紹介

これが一番うまく行った。

参考:jQuery FadeThis

JS

/*
* jQuery FadeThis - v1.0.0
* A lightweight, simple, yet powerful jQuery plugin for appear-as-you-scroll features.
* http://jqueryfadethis.com
*
* Made by lwiesel
* Under MIT License
*/
!function(a,b,c){var d=null,e=[],f=a(b),g=function(){};g.prototype={globals:{pluginName:"fadeThis",bufferTime:300},defaults:{baseName:"slide-",speed:500,easing:"swing",offset:0,reverse:!0,distance:50,scrolledIn:null,scrolledOut:null},init:function(a,b){this.addElements(a,b),this._setEvent(),this._checkVisibleElements()},addElements:function(d,e){var f=d===c.body?b:d,g=a(f===b?"body":f),h=this,i=e&&e.baseName?e.baseName:this.defaults.baseName;return g.is("[class^='"+i+"']")?h._addElement(g,e):g.find("[class^='"+i+"']").each(function(){h._addElement(a(this),e)}),g},_addElement:function(b,c){var d=b.data("plugin-options"),f=a.extend({},this.defaults,c,d),g={element:b,options:f,invp:!1};return e.push(g),console.log(g),this._prepareElement(g),b},_prepareElement:function(a){var b={opacity:0,visibility:"visible",position:"relative"},c=null;if(a.element.hasClass(a.options.baseName+"right"))c="left";else if(a.element.hasClass(a.options.baseName+"left"))c="right";else if(a.element.hasClass(a.options.baseName+"top"))c="bottom";else{if(!a.element.hasClass(a.options.baseName+"bottom"))return!1;c="top"}b[c]=a.options.distance,a.element.css(b)},_setEvent:function(){var a=this;f.on("scroll",function(b){d||(d=setTimeout(function(){a._checkVisibleElements(b),d=null},a.globals.bufferTime))})},_checkVisibleElements:function(b){var c=this;a.each(e,function(a,d){c._isVisible(d)?d.invp||(d.invp=!0,c._triggerFading(d),d.options.scrolledIn&&d.options.scrolledIn.call(d.element,b),d.element.trigger("fadethisscrolledin",b)):d.invp&&(d.invp=!1,d.options.reverse&&c._triggerFading(d,!1),d.options.scrolledOut&&d.options.scrolledOut.call(d.element,b),d.element.trigger("fadethisscrolledout",b))})},_isVisible:function(a){var b=f.scrollTop()+a.options.offset,c=b+f.height()-2*a.options.offset,d=a.element.offset().top,e=d+a.element.height();return e>=b&&c>=d&&c>=e&&d>=b},_triggerFading:function(a,b){b="undefined"!=typeof b?b:!0;var c={opacity:1},d={opacity:0},e=null;if(a.element.hasClass(a.options.baseName+"right"))e="left";else if(a.element.hasClass(a.options.baseName+"left"))e="right";else if(a.element.hasClass(a.options.baseName+"top"))e="bottom";else{if(!a.element.hasClass(a.options.baseName+"bottom"))return!1;e="top"}c[e]=0,d[e]=a.options.distance,b?a.element.stop(!0).animate(c,a.options.speed,a.options.easing):a.element.stop(!0).animate(d,a.options.speed,a.options.easing)}},g.defaults=g.prototype.defaults,g.globals=g.prototype.globals,b.Plugin=new g,a.fn[g.globals.pluginName]=function(c){return this.each(function(){a.data(b,"plugin_"+g.globals.pluginName)?a.data(this,"plugin_"+g.globals.pluginName)||a.data(this,"plugin_"+g.globals.pluginName,b.Plugin.addElements(this,c)):(a.data(b,"plugin_"+g.globals.pluginName,"set"),a.data(this,"plugin_"+g.globals.pluginName,b.Plugin.init(this,c)))}),this}}(jQuery,window,document);

本体とjs読み込み(1.4以上推奨らしい)

<script src="jquery.js"></script>
<script src="jquery.fadethis.min.js"></script>

あとこれをbodyの閉じタグの前に。

<script>$(window).fadeThis();</script>

あとはこんな感じで。
top/bottom/left/rightの切り替えで出てくる方向が変わるヨ

<div class="slide-left"></div>

headerやcontentsのmargin-top入れて上の要素分下げる

WordPressで開発するときとか、ヘッダーをabsoluteとかfixedにするときとか、とりあえずヘッダとかにコンテンツが隠れちゃうってことシバシバあるじゃないですか。
そゆときには以下を使う。これでheaderの下のcontentsがヘッダに隠れないよ!

色々変な値入ってるからカスタマイズしてね。

jQuery(function($){
var headerHight = Number($( 'header#masthead' ).height()) - 6;

$( '#content' )
.css({
'margin-top' : headerHight + 'px',
})

z$( 'header#masthead' )
.css({
'margin-top' : $( '#wpadminbar' ).height() + 'px',
})

});

jQuery(function($){
if($('#wpadminbar').length){
var height1 = $('#wpadminbar').height();
var height2 = $('header#masthead').height();
var height3 = 23;
$('.breadcrumb').css('top',height1+height2+height3+'px');
} else {
var height2 = $('header#masthead').outerHeight(true);
var height3 = 23;
$('.breadcrumb').css('top',height2+height3+'px');
}
});

jQuery(function($){
if($('#wpadminbar').length){
var height1 = $('#wpadminbar').height();
var height2 = $('header#masthead').height();
var height3 = 103;
$('h1.page-entry-header').css('top',height1+height2+height3+'px');
} else {
var height2 = $('header#masthead').outerHeight(true);
var height3 = 103;
$('h1.page-entry-header').css('top',height2+height3+'px');
}
});

文字サイズ変更ボタン

結構医療系のサイトだと文字サイズの変更ボタンが必要だったりするのでそれの備忘録。

JS

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="common/js/jquery.cookie.js"></script>
<script src="common/js/fontsize.js"></script>

fontsize.js

jQuery(function($){
//変数にクッキー名を入れる
var history = $.cookie('fontSize');
//適用する箇所を指定。今回は部分的に#test内のpに
var elm = $('body');
//変数が空ならfontMを、空でなければクッキーに保存しておいたものを適用
if(!history){
elm.addClass('fontS');
$('#fontS').addClass('active');
}else{
elm.addClass(history);
$('#'+history).addClass('active');
}
//ボタンをクリックしたら実行
$('li','.mod_headerbox_size').click(function(){
//activeでないボタンだった場合のみ動作
if(!$(this).hasClass('active')){
//現在activeのついているclassを削除
$('.active').removeClass('active');
//クリックしたボタンをactive
$(this).addClass('active');
//クリックした要素のID名を変数にセット
var setFontSize = this.id;
//クッキーに変数を保存
$.cookie('fontSize', setFontSize);
//一度classを除去して、変数をclassとして追加
elm.removeClass().addClass(setFontSize);
}
});
});

jquery.cookie.js

/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// CAUTION: Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};

HTML

<div class="mod_headerbox_size">
<ul>
<li id="fontS"><span><img width="30" height="60" alt="小さいサイズ" src="common/img/size_s.jpg"></span></li>
<li id="fontM"><span><img width="30" height="60" alt="少し大きいサイズ" src="common/img/size_m.jpg"></span></li>
<li id="fontL"><span><img width="30" height="60" alt="大きいサイズ" src="common/img/size_b.jpg"></span></li>
</ul>
<!--mod_headerbox_size_end--></div>

CSS

/* fontsize
-----------------------------------------*/
.fontS { font-size: 75% }
.fontM { font-size: 85% }
.fontL { font-size: 95% }

/* mod_headerbox_size
-----------------------------------------*/
.mod_headerbox_size {
width: 90px;
position:relative;
overflow:hidden;
}
.mod_headerbox_size ul {
}
.mod_headerbox_size ul li {
float: left;
width:30px;
height: 30px;
overflow: hidden;
}
.mod_headerbox_size ul li span {
display: block;
cursor: pointer;
}
.mod_headerbox_size ul li.active span {
margin-top: -30px;
}
.mod_headerbox_size ul li span:hover{
margin-top:-30px;
}

画像。

これでできるよ

クリックで隠れていた要素が表示される仕組み

コンテンツ量が多いページを作るときに、内容を隠してクリックでその下あたりに表示させたい時のJS!

HTML

<!-- 表示ボタン -->
<p class="openBtn"><i class="fa fa-chevron-down faColor"> </i>★★★項目名★★★</p>

<!-- 説明文 -->
<p class="textArea">★★★説明文★★★</p>

JS

$(function(){
$(".openBtn").click(function(){
$($(this).next(".textArea")).animate(
{height: "toggle", opacity: "toggle"},
"nomal"
);
});
});
JS(WPのとき)
jQuery(function($){
$(".openBtn").click(function(){
$($(this).next(".textArea")).animate(
{height: "toggle", opacity: "toggle"},
"nomal"
);
});
});

CSS

/* 表示ボタン */
.openBtn {
cursor: pointer;
padding: 10px;
border: 1px solid #9FD6D2;
border-left: 10px solid #9FD6D2;
color: #666;
}

/* 説明文 */
.textArea {
display: none;
padding: 10px 10px 30px 50px;
color: #666;
}

/* 表示ボタン ー 逆三角アイコン */
.faColor {
color: #9FD6D2;
}