Кнопка выбора языка html

Переключатель языков без плагина

Самописный код выгодно отличается от плагина тем, что не содержит в себе дополнительную нагрузку, которой перегружены все плагины, так-как они создаются для разносторонних потребностей пользователей.

Одним нужен маленький переключатель, другим большой, третьим нужен и автопереводчик с редактором, и админку, и библиотеки, вот разработчики и суют всё в одну коробочку, а до кучи ещё и рекламку и пару ссылочек и т.д., и т.п, зато бесплатно.

. blok text-align : center ;
width : 89px ;
>
. blok a text-decoration : none ;
display : block ;
transition : .5s linear ;

>
. blok ul list-style : none ;
margin : 0 ;
padding : 0 ;

>
. topmenu > li display : block ;
position : relative ;
top : 0 ;
left : 0 ;
margin-bottom : 2px ;
>
. submenu position : absolute ;
left : 0 ;
top : 0 ;
z-index : 5 ;
width : 89px ;
visibility : hidden ;
opacity : 0 ;
transform : translateY(10px) ;
transition : .5s ease-in-out ;
>
. submenu li position : relative ;
top : 0 ;
left : 0 ;
>
. submenu .submenu position : absolute ;
top : 0 ;
left : calc(100% — 1px) ;
left : -webkit-calc(100% — 1px) ;
>
. blok li:hover > .submenu visibility : visible ;
opacity : 1 ;
transform : translateY(0px) ;
>

Как видите — чистый html+css.

В темах оформления CMS, обычно задаются свойства для списков (теги li, ul, ol), поэтому, возможно, в теги li нужно будет ввести классы, и задать этим классам свои свойства позиционирования.

Картинки можно, и даже лучше, нарезать в Паинте прямо отсюда. В сервисах изображений вы ничего лучше не найдёте.

Желаю всем плодотворной работы.

Источник

Creating an accessible language picker

In this article, we’ll go through the steps of creating a custom language picker and keeping it accessible.

By Claudia Romano Follow author on Twitter

Creating an accessible language picker

We recently published the Language Picker component. It’s a common widget to find on a website but you need to keep a few things in mind during development if you want it to be accessible.

Let’s do this! #

The component we build in this tutorial is based on the CodyHouse framework.

👋 First time you hear about the CodyHouse Framework?

Let’s go through the steps of creating our custom language picker.

1. Initial HTML structure #

Our starting point will be a (with the list of all possible languages) and its element:

 

This is what users with JavaScript disabled will see; the form submission can be used to handle the language selection.

Note that each element has a lang attribute (that specifies the language of the text) and that we used the labels in their original language (for example, I’m Italian so I’m expecting to find ‘Italiano’ as an option, rather than ‘Italian’).

2. Custom Structure #

Using JavaScript, we can replace the default with a new structure. We’ll need:

  • a which will be used as a trigger to open the language list;
  • a dropdown element with the list of all available languages.

First, lets’ start by defining the HTML structure that we want to use for these elements.

Читайте также:  Php imagick fill color

For the element, we’ll have:

Let’s analyze the aria attributes we have added to this element:

  • aria-label : this is a string that labels our button and it’s announced when the element is selected. It is composed of the selected language (e.g., ‘English’) and the text of the element (e.g., ‘Select your language’). You need this attribute as the may not have a visible text (for example, you just want to show a flag icon inside it).
  • aria-expanded : by default, it is set to false (it tells you the language list is not expanded), but it will be changed to true when the language dropdown is visible.
  • aria-controls : this attribute links the to the element it controls (language list). It is set equal to the id of the dropdown.

The element inside the button is used to create the flag icon and has an aria-hidden=»true» (it does not provide any additional info so we don’t want it to be announced by Screen Readers).

Let’s now take a look at the language list final HTML:

We have a .language-picker__dropdown element with an id equal to the aria-controls value of our .

We have added an aria-describedby equal to the id of the

element inside it. This will provide a description for the dropdown that will be announced by SR when the element is selected.

The

element inside the .language-picker__dropdown has a class of sr-only : this class (defined inside the Codyhouse Framework) can be used to visually hide an element, leaving it accessible to SR. You can read more about that on the accessibility global documentation page.

Inside the .language-picker__dropdown , we have an unordered list of languages with a role of listbox (this is a list of options which users can choose).

One important thing to add here is the lang attribute (defined for each element in the original HTML structure); this way SR will know how to pronounce the language label.

Finally, we have added an aria-selected=»true» to the selected language link.

Now that we have the final HTML structure, we can implement the JS code that will handle its creation.

First, we can define a LanguagePicker object:

var LanguagePicker = function(element) < this.element = element; this.select = this.element.getElementsByTagName('select')[0]; this.options = this.select.getElementsByTagName('option'); this.pickerId = this.select.getAttribute('id'); // .. initLanguagePicker(this); >; //initialize the LanguagePicker objects var languagePicker = document.getElementsByClassName('js-language-picker'); if( languagePicker.length > 0 ) < for( var i = 0; i < languagePicker.length; i++) < new LanguagePicker(languagePicker[i]); >>

The initLanguagePicker function can take care of creating the custom structure:

Now that the HTML structure is in place, we can style it:

.js .language-picker__form < // if JavaScript is enabled, hide the default form element display: none; >.language-picker__dropdown < position: absolute; left: 0; top: 100%; width: 200px; background-color: var(--color-bg); box-shadow: var(--shadow-sm); padding: var(--space-xxs) 0; border-radius: 0.25em; z-index: var(--zindex-popover); // hide the language list by default visibility: hidden; opacity: 0; transition: .2s ease-out; >.language-picker__button[aria-expanded="true"] + .language-picker__dropdown < // show the language list when the aria-expanded attribute of the button element is true visibility: visible; opacity: 1; transform: translateY(4px); >

3. Handling Events #

We still need to handle the click on the element that will toggle the dropdown visibility.

// click events picker.trigger.addEventListener('click', function()< toggleLanguagePicker(picker); >); function toggleLanguagePicker(picker, bool) < var ariaExpanded; if(bool) < ariaExpanded = bool; >else < ariaExpanded = picker.trigger.getAttribute('aria-expanded') == 'true' ? 'false' : 'true'; >picker.trigger.setAttribute('aria-expanded', ariaExpanded); if(ariaExpanded == 'true') < picker.dropdown.addEventListener('transitionend', function cb()< // once the dropdown is visible ->move focus from trigger to the first language in the list picker.firstLanguage.focus(); picker.dropdown.removeEventListener('transitionend', cb); >); > >;

When the button is clicked, we change the aria-expanded attribute of the (from false to true and vice-versa); this will update the dropdown visibility (check the CSS code at the end of step 2 for more info about the style).

Читайте также:  Css background image несколько картинок

When the dropdown is open (aria-expanded == true), we also move the focus from the to the first language in the list.

That’s pretty much all we had to do in JavaScript!

One last improvement (for keyboard navigation) would be to close the language list when pressing ‘Esc’:

// listen for key events window.addEventListener('keyup', function(event)< if( event.keyCode && event.keyCode == 27 || event.key && event.key.toLowerCase() == 'escape' ) < // close language picker on 'Esc' pickerArray.forEach(function(element)< moveFocusToTrigger(element); // if focus is still within the dropdown, move it to dropdown trigger toggleLanguagePicker(element, 'false'); // close dropdown >); > >);

Before using the toggleLanguagePicker function (that closes the dropdown), we use the moveFocusToTrigger function; this function checks if the focus is still within the dropdown element and, if it is, it moves it back to the button trigger:

function moveFocusToTrigger(picker) < if(picker.trigger.getAttribute('aria-expanded') == 'false') return; if(document.activeElement.closest('.language-picker__dropdown') == picker.dropdown) picker.trigger.focus(); >;

That’s it! You can find a preview (and the full code) on the Language Picker component demo page.

We use cookies to give you the best possible website experience. By using CodyHouse, you agree to our Privacy Policy.

Источник

Изменить язык сайта с помощью кнопки HTML

В PHP я хочу изменить язык (английский, немецкий и т.д.) на сайте при нажатии кнопки. Правильно ли это подходит к этой проблеме?

 else < include("header.php"); >?>     

6 ответов

и получить языки и сохранить их в файле cookie и включить файл в соответствии с файлом cookie, например

if ( !empty($_GET['language']) ) < $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl'; >else < $_COOKIE['language'] = 'nl'; >setcookie('language', $_COOKIE['language']); 
if ( $_COOKIE['language'] == "en") < include("headerEn.php"); >else < include("header.php"); >?> 

Я думаю, что другая часть должна быть else if (empty($_COOKIE[‘language’])) , чтобы избежать сброса языка на ‘nl’, когда cookie (а не запрос) содержит выбранный язык.

Всегда полезно иметь значение по умолчанию, так что вы никогда не окажетесь на неязычном сайте.

$language = $_REQUEST["language"]; $default_header="myheaderXXX.php"; switch ($language)

И затем создайте такие ссылки:

Чтобы дать решение без изменения вашего подхода, вы можете сделать это следующим образом.

 else < include("header.php"); >?>    

Если вы хотите сохранить выделение, вы можете сохранить это значение в базе данных или сеансе.

Читайте также:  Javascript full stack react

Вы не можете изменить переменную в PHP через html. PHP является серверным сервером. Клиентский интерфейс HTML

Вы можете использовать GET переменные, чтобы изменить его. Это самый простой способ сделать это.

Вы можете реализовать тот же код, что и этот. Я отредактировал ваш код.

      

Попробуйте сохранить это значение $language в переменной session. Когда перезагрузка страницы проверяет, установлена ​​ли переменная сеанса или нет.

Если установлено, используйте $language

Ещё вопросы

  • 1 Как получить ButtonDrawable из флажка в API 21?
  • 1 Как исправить этот код, чтобы он работал правильно
  • 0 Рафаэль, рисовать и изменять размеры вертикальных линий
  • 0 Получить значение атрибута внутри тега ввода с помощью JavaScript
  • 1 Атрибуты класса, определенные в __init __ (), против атрибутов, определенных методом класса
  • 1 Как создать внутренние ссылки с JS-XLSX
  • 0 Chrome и Opera удаляют данные записи при редактировании записи
  • 0 SQLi Выбрать переменные
  • 0 Экспресс и Джейд: цикл и создание динамических идентификаторов
  • 0 SSRS: несколько ссылок HTML в одном столбце не отображаются правильно при экспорте в Excel
  • 1 Отправить письмо программно
  • 0 Как максимизировать и минимизировать div на клике в jquerymobile
  • 0 Ошибка определения функции C ++ (передача параметров)
  • 1 Декомпрессия ZLib
  • 0 Класс не работает со статической переменной в C ++
  • 0 параметр по умолчанию ostream в функции шаблона
  • 1 Обслуживание статической страницы из пользовательского действия scala в Play Framework
  • 0 Найти высоту элемента, содержащего текст
  • 0 Привязка модели AngularJS не работает, если модель и привязка установлены jQuery
  • 0 g ++: CreateProcess: нет такого файла или каталога [дубликата]
  • 0 сгенерированный файл MSM
  • 1 Обрабатывать всплывающее окно JavaScript внутри div
  • 1 Не удается разрешить метод updateUI ()
  • 1 Передача метода в lodash с помощью vue дает ‘Ожидаемая функция’
  • 1 Клиент SignalR js неправильный порт сервера
  • 0 тег якоря не работает должным образом во всплывающем окне div
  • 0 Объявите переменную в базе данных MySQL «только для чтения»
  • 1 Отсутствие практического понимания использования Play + Scala против JavaScript
  • 0 Функция возвращает неправильный номер?
  • 0 javaScript Fade-In OnLoad
  • 0 Нижний колонтитул отображается под заголовком навигации
  • 0 AngularJS — директива не загружена
  • 0 Что я вернусь к удаленному методу JQuery?
  • 0 Конфликт между двумя JavaScript. Плавная прокрутка между якорями и обратно
  • 1 Использование HttpResponseMessage для просмотра ошибок
  • 0 angular $ resource получает дополнительную информацию
  • 0 Angularjs доступ к представлениям с прямым URL
  • 1 Как отправить объекты разных классов в одном сообщении Json, чтобы их можно было десериализовать с помощью Gson?
  • 0 Использование среза Javascript внутри углового выражения
  • 0 Booleans не работает правильно
  • 1 Android Studio SharedPreferences и внутреннее хранилище не работают
  • 1 почему в android mobile version 8.1 [oreo] не работает сервис Floating Widget? [приложение становится раздавленным]
  • 0 Простой селектор jQuery
  • 0 отредактируйте htaccess, чтобы сделать его нечувствительным к регистру
  • 0 Невозможно изменить цвет шрифта всех элементов в строках и столбцах табличных тегов
  • 0 выберите для обновления дважды к той же таблице ключом diffrenet, вызывающим взаимоблокировку в MySQL
  • 0 Ионный список и задержка
  • 0 fullcalendar вместе с вложениями в календарь Google
  • 1 Изменение состояния веб-приложения во время выполнения
  • 0 Имя поля / столбца MYSQL и PHP как переменная

Источник

Оцените статью