css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="comparison-block">
  <span class="comparison-arrow"></span>
  <div class="comparison-before-img"><img src="https://blanks.site/assets/images/uploads/post44_1.jpg" alt="加工前の写真(左側の写真)"></div>
  <div class="comparison-after-img"><img src="https://blanks.site/assets/images/uploads/post44_2.jpg" alt="加工後の写真(右側の写真)"></div>
</div>





            
          
!
            
              .comparison-block{
  width: 100%;
  max-width: 640px;
  position: relative;
  margin: 0 auto;
  //選択時に画像の色を変えないようにする
  &::selection{
    background-color: transparent;
  }
  &::-moz-selection{
    background-color: transparent;
  }
  *{
    &::selection{
      background-color: transparent;
    }
    &::-moz-selection{
      background-color: transparent;
    }    
  }
}
.comparison-before-img{
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  z-index: 5;
}
.comparison-after-img{
  position: relative;
  z-index: 1;
  img{
    width: 100%;
  }
}
//境界線のcss
.comparison-arrow{
  background-color: #fff;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 2px;
  height: 100%;
  left: 50%;
  cursor: pointer;
  &:after{
    content: '';
    display: block;
    width: 30px;
    height: 30px;
    border-radius: 15px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    margin-top: -15px;
    left: -14px;
  }
}
            
          
!
            
              const blockElements = document.getElementsByClassName('comparison-block');      //arrow,before-img,after-imgを囲む要素
const elements = document.getElementsByClassName('comparison-arrow');           //ドラッグできる境界線の要素
const beforeImages = document.getElementsByClassName('comparison-before-img');  //変更前の画像を囲むdivタグ要素
let device = '';         // デバイス
let move_start_x = 0;    // 境界線のX線上の初期値
let move_flg = false;    // マウスダウンをしているかどうかのbool値
let dragMoveFunc = '';  // mouseDrag関数を格納するための変数
let startEvent = '';     // ドラッグ開始イベント
let moveEvent = '';      // ドラッグ中のイベント
let endEvent = '';       // ドラッグ終了のイベント

//UAによるデバイス判定
if (navigator.userAgent.indexOf('iPhone') > 0 || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Windows Phone') > 0 || navigator.userAgent.indexOf('iPad') > 0 || navigator.userAgent.indexOf('Android') > 0){
  device = 'smt';
}else{
  device = 'pc';
}

//イベントの種類を設定
if( device == 'smt' ){
  //スマホ時のイベントの種類
  startEvent = 'touchstart';
  moveEvent = 'touchmove';
  endEvent = 'touchend';
}else{
  //パソコン時のイベントの種類
  startEvent = 'mousedown';
  moveEvent = 'mousemove';
  endEvent = 'mouseup'; 
}

//マウスダウン、タッチスタート時の関数
function dragStart(e){
  let event = '';
  if( device === 'smt' ) {
    event = e.changedTouches[0];
  } else {
    event = e;
  }

  move_flg = true;
  let for_flag = false;
  let targetElement = '';  //arrow要素
  
  //PCとスマホでは「startEvent」の対象要素が違うため、arrow要素を取得するためにそれぞれ違う処理を行う
  if( device == 'smt' ){
    for(let childEle of this.children){
      for( let childEleClass of childEle.classList ){
        if( childEleClass == 'comparison-arrow' ){
          move_start_x = event.pageX - childEle.offsetLeft;
          targetElement = childEle;
          break;
          for_flag = true;
        }
      }
      if( for_flag ){ break; }
    }
  }else{
    move_start_x = event.pageX - this.offsetLeft;
    targetElement = this;
  }
  dragMoveFunc = function(e){ dragMove(e,targetElement) }  //イベントの解除を有効にするためにdragMoveを一度dragMoveFuncに格納
  document.body.addEventListener(moveEvent, dragMoveFunc , false);  //dragMoveFuncを実行
}

//マウスムーブ、タッチムーブ時の関数
function dragMove(e,ele){
  let event = '';
  if( device === 'smt' ) {
    event = e.changedTouches[0];
  } else {
    event = e;
  }
  // move_flgは mouseDownを通るとtrueになり、mouseUpを通るとfalseになる
  if( move_flg ){
    let arrowElement = ele;
    let blockElement = ele.parentNode;
    let for_flag = false;
    let beforeImgElement = '';
    // イベントが発火した blockElements の子要素の「.comparison-before-img」を取得
    for(let childEle of blockElement.children){
      for( let childEleClass of childEle.classList ){
        if( childEleClass == 'comparison-before-img' ){
          beforeImgElement =  childEle;
          break;
          for_flag = true;
        }
      }
      if( for_flag ){ break; }
    }
    let X = event.clientX - move_start_x;
    let maxX = blockElement.clientWidth;
    // arrow要素が全体を囲んでいる要素からはみ出さないように移動の下限、上限を設定
    if( X < 0 ){
      arrowElement.style.left = '0px';            //arrow要素のx値
      beforeImgElement.style.width = '0px';       //before-imgのwidth
    }else if( X > maxX ){
      arrowElement.style.left = `${maxX}px`;      //arrow要素のx値
      beforeImgElement.style.width = `${maxX}px`; //before-imgのwidth
    }else{
      arrowElement.style.left = `${X}px`;          //arrow要素のx値
      beforeImgElement.style.width =  `${X}px`;    //before-imgのwidth
    }    
  }
}

//マウスアップ、タッチエンド時の関数
function dragEnd(){
  move_flg = false;
  // dragMoveFuncを解除する
  document.body.removeEventListener(moveEvent, dragMoveFunc, false);
}

//ロード時の関数
function loadFunc(){
  for( let i = 0 ; i < elements.length ; i++ ){
    let w = blockElements[i].clientWidth;
    // 「.before-img」のwidthを親要素の半分にする
    beforeImages[i].style.width = `${w/2}px`;
    // 「.before-img」の子要素の画像サイズを変換
    beforeImages[i].children[0].style.width =`${w}px`;
  }
}

//リサイズ時の関数
function resizeFunc(){
  for( let i = 0 ; i < elements.length ; i++ ){
    let w = blockElements[i].clientWidth;
    // arrow要素を全体の真ん中の位置に移動させる
    elements[i].style.left =`${w/2}px`;
    // 「.before-img」のwidthを親要素の半分にする
    beforeImages[i].style.width = `${w/2}px`;
    // 「.before-img」の子要素の画像サイズを変換
    beforeImages[i].children[0].style.width = `${w}px`;
  }
}


//関数の実行
if( device == 'smt' ){
  for( let i = 0 ; i < elements.length ; i++ ){
    //スマホ時はユーザビリティ向上の為、イベント発火の対象はarrow部分でなく、画像を囲む要素
    blockElements[i].addEventListener(startEvent, dragStart, false);
  }  
}else{
  for( let i = 0 ; i < elements.length ; i++ ){
    elements[i].addEventListener(startEvent, dragStart, false);
  }  
}
document.body.addEventListener(endEvent, dragEnd, false);
window.addEventListener("load", loadFunc, false);
window.addEventListener("resize", resizeFunc, false);
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console