The Islamic State group claimed it had carried out the attack.

Mr. Omar said that heavily armed men — he said that he did not know the precise number, but had seen two — took over the commission’s administration building, one of several structures in the complex.

“They were very close to us, some 20 meters or so, they were armed with machine guns,” he said, adding that they “went through the building and didn’t let anyone move.”

“Meanwhile, a security force came and besieged the building,” he said.

The gunmen apparently had suicide vests, which they detonated as security forces closed in. Images posted on social media showed smoke billowing from the building.

Libya has been torn by war and terrorism since the 2011 uprising that overthrew the dictator Muammar el-Qaddafi. Elections are planned for later this year, but some opponents of the government have been determined to disrupt the process.

“My understanding is that there were two or three attackers who moved in on the administrative building,” said Otman Gajiji, a former chairman of the electoral commission. “One of them went upstairs and started setting the selections materials on fire, while a second one was downstairs providing cover. It seems that their target was the elections materials stored in the administrative building.”