编辑文件:lang-switcher.js
/** * ClothB2B Child — language switcher behavior. * * The switcher markup (functions.php, hook astra_masthead) is pure HTML/CSS and * already opens on :hover / :focus-within as a no-JS fallback. This script adds * a proper click-toggle, outside-click + Escape to close, and keeps the toggle * button's aria-expanded in sync — so the dropdown is usable with a mouse, on * touch devices, and from the keyboard. Vanilla, no dependencies, footer-loaded. */ ( function () { 'use strict'; function closeSwitcher( sw ) { sw.classList.remove( 'is-open' ); var toggle = sw.querySelector( '.cb-lang-toggle' ); if ( toggle ) { toggle.setAttribute( 'aria-expanded', 'false' ); } } function openSwitcher( sw ) { sw.classList.add( 'is-open' ); var toggle = sw.querySelector( '.cb-lang-toggle' ); if ( toggle ) { toggle.setAttribute( 'aria-expanded', 'true' ); } } document.addEventListener( 'DOMContentLoaded', function () { var switchers = document.querySelectorAll( '.cb-lang-switcher' ); for ( var i = 0; i < switchers.length; i++ ) { ( function ( sw ) { var toggle = sw.querySelector( '.cb-lang-toggle' ); if ( ! toggle ) { return; } toggle.addEventListener( 'click', function ( e ) { e.preventDefault(); if ( sw.classList.contains( 'is-open' ) ) { closeSwitcher( sw ); } else { openSwitcher( sw ); } } ); } )( switchers[ i ] ); } // Click outside any open switcher closes it. document.addEventListener( 'click', function ( e ) { for ( var j = 0; j < switchers.length; j++ ) { if ( switchers[ j ].classList.contains( 'is-open' ) && ! switchers[ j ].contains( e.target ) ) { closeSwitcher( switchers[ j ] ); } } } ); // Escape closes the open switcher and returns focus to its toggle. document.addEventListener( 'keydown', function ( e ) { if ( 'Escape' !== e.key ) { return; } for ( var k = 0; k < switchers.length; k++ ) { if ( switchers[ k ].classList.contains( 'is-open' ) ) { closeSwitcher( switchers[ k ] ); var t = switchers[ k ].querySelector( '.cb-lang-toggle' ); if ( t ) { t.focus(); } } } } ); } ); }() );
保存
返回